<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <!-- hexo-inject:begin --><!-- hexo-inject:end --><meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222" media="(prefers-color-scheme: light)">
<meta name="theme-color" content="#222" media="(prefers-color-scheme: dark)"><meta name="generator" content="Hexo 5.4.2">

  <link rel="apple-touch-icon" sizes="180x180" href="https://static.xiaosige.com/img/favicon.png">
  <link rel="icon" type="image/png" sizes="32x32" href="https://static.xiaosige.com/img/favicon.png">
  <link rel="icon" type="image/png" sizes="16x16" href="https://static.xiaosige.com/img/favicon.png">
  <link rel="mask-icon" href="https://static.xiaosige.com/img/favicon.png" color="#222">
  <meta name="baidu-site-verification" content="WZilU4QiSZ">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.1/css/all.min.css">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/animate.css@3.1.1/animate.min.css" integrity="sha256-PR7ttpcvz8qrF57fur/yAx1qXMFJeJFiA6pSzWi0OIE=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui@5.0.31/dist/fancybox/fancybox.css" integrity="sha256-gkQVf8UKZgQ0HyuxL/VnacadJ+D2Kox2TCEBuNQg5+w=" crossorigin="anonymous">

<script class="next-config" data-name="main" type="application/json">{"hostname":"www.xiaosige.com","root":"/","images":"/images","scheme":"Gemini","darkmode":true,"version":"8.26.0","exturl":false,"sidebar":{"position":"left","width_expanded":320,"width_dual_column":240,"display":"post","padding":18,"offset":12},"hljswrap":false,"codeblock":{"theme":{"light":"atom-one-dark-reasonable","dark":"atom-one-dark-reasonable"},"prism":{"light":"prism-tomorrow","dark":"prism-tomorrow"},"copy_button":{"enable":true,"style":"mac"},"fold":{"enable":false,"height":500},"language":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"mediumzoom":false,"lazyload":true,"pangu":false,"comments":{"style":"tabs","active":"changyan","storage":true,"lazyload":true,"nav":null,"activeClass":"changyan"},"stickytabs":false,"motion":{"enable":true,"async":false,"duration":200,"transition":{"menu_item":"fadeInDown","post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"},"path":"/search.xml","localsearch":{"enable":true,"top_n_per_article":1,"unescape":false,"preload":true,"trigger":"auto"}}</script><script src="/js/config.js" defer></script>

    <meta property="og:type" content="article">
<meta property="og:title" content="Docker容器网络和Docker容器网络配置">
<meta property="og:url" content="https://www.xiaosige.com/post/2f93af4e.html">
<meta property="og:site_name" content="小四儿">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://www.xiaosige.com/post/2f93af4e/dockernw001.png">
<meta property="og:image" content="https://www.xiaosige.com/post/2f93af4e/dockernw002.png">
<meta property="og:image" content="https://www.xiaosige.com/post/2f93af4e/dockernw003.png">
<meta property="og:image" content="https://www.xiaosige.com/post/2f93af4e/dockernw004.png">
<meta property="og:image" content="https://www.xiaosige.com/post/2f93af4e/dockernw005.png">
<meta property="og:image" content="https://www.xiaosige.com/post/2f93af4e/dockernw006.png">
<meta property="og:image" content="https://www.xiaosige.com/post/2f93af4e/dockernw007.png">
<meta property="article:published_time" content="2021-10-11T13:20:11.000Z">
<meta property="article:modified_time" content="2022-10-11T16:32:20.223Z">
<meta property="article:author" content="leeze">
<meta property="article:tag" content="Docker">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://www.xiaosige.com/post/2f93af4e/dockernw001.png">


<link rel="canonical" href="https://www.xiaosige.com/post/2f93af4e.html">


<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"zh-CN","comments":true,"permalink":"https://www.xiaosige.com/post/2f93af4e.html","path":"post/2f93af4e.html","title":"Docker容器网络和Docker容器网络配置"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>Docker容器网络和Docker容器网络配置 | 小四儿</title>
  

  <script src="/js/third-party/analytics/baidu-analytics.js" defer></script>
  <script async src="https://hm.baidu.com/hm.js?7a645cfcecaf8f711cd7518386adcc74"></script>







  
  <script src="https://cdn.jsdelivr.net/npm/animejs@3.2.1/lib/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous" defer></script>
  <script src="https://cdn.jsdelivr.net/npm/@next-theme/pjax@0.6.0/pjax.min.js" integrity="sha256-vxLn1tSKWD4dqbMRyv940UYw4sXgMtYcK6reefzZrao=" crossorigin="anonymous" defer></script>
  <script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui@5.0.31/dist/fancybox/fancybox.umd.js" integrity="sha256-a+H7FYzJv6oU2hfsfDGM2Ohw/cR9v+hPfxHCLdmCrE8=" crossorigin="anonymous" defer></script>
  <script src="https://cdn.jsdelivr.net/npm/lozad@1.16.0/dist/lozad.min.js" integrity="sha256-mOFREFhqmHeQbXpK2lp4nA3qooVgACfh88fpJftLBbc=" crossorigin="anonymous" defer></script>
<script src="/js/utils.js" defer></script><script src="/js/motion.js" defer></script><script src="/js/sidebar.js" defer></script><script src="/js/next-boot.js" defer></script><script src="/js/pjax.js" defer></script>

  <script src="https://cdn.jsdelivr.net/npm/hexo-generator-searchdb@1.5.0/dist/search.js" integrity="sha256-xFC6PJ82SL9b3WkGjFavNiA9gm5z6UBxWPiu4CYjptg=" crossorigin="anonymous" defer></script>
<script src="/js/third-party/search/local-search.js" defer></script>

  <script class="next-config" data-name="pdf" type="application/json">{"object_url":{"url":"https://cdn.jsdelivr.net/npm/pdfobject@2.3.1/pdfobject.min.js","integrity":"sha256-jI72I8ZLVflVOisZIOaLvRew3tyvzeu6aZXFm7P7dEo="},"url":"/lib/pdf/web/viewer.html"}</script>
  <script src="/js/third-party/tags/pdf.js" defer></script>



  <script src="/js/third-party/fancybox.js" defer></script>



  
  <script data-pjax async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>




  <script src="https://cdn.jsdelivr.net/npm/quicklink@3.0.1/dist/quicklink.umd.js" integrity="sha256-44BednzIpUeQJcY8qtLyarFu0UCCTbgmWOvaoehiFQQ=" crossorigin="anonymous" defer></script>
  <script class="next-config" data-name="quicklink" type="application/json">{"enable":true,"home":true,"archive":true,"delay":true,"timeout":3000,"priority":true,"ignores":null,"url":"https://www.xiaosige.com/post/2f93af4e.html"}</script>
  <script src="/js/third-party/quicklink.js" defer></script>
<!-- https://www.layuicdn.com/layui/css/layui.css -->
<script src="https://www.layuicdn.com/layui/layui.js"></script>

<script src="https://cdn.jsdelivr.net/npm/jquery@3.7.1/dist/jquery.min.js"></script>


<script src="https://cdn.jsdelivr.net/npm/gsap@3.12.4/dist/gsap.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/splitting@1.0.6/dist/splitting.min.js"></script>
<style type="text/css">
    .char{
      font-variation-settings: 'wght' var(--weight, 100);
      color: hsl(var(--hue), calc(var(--saturation) * 1%), 65%);
    }
</style>



<link rel="stylesheet" type="text/css" href="/css/shake.css" />


<link rel="stylesheet" type="text/css" href="/css/hover.css" />


<link rel="stylesheet" type="text/css" href="/zone/css/i_hover.css" />
<link rel="stylesheet" type="text/css" href="/css/injector/main.css" /><link rel="preload" as="style" href="/css/injector/light.css" /><link rel="preload" as="style" href="/css/injector/dark.css" />
  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>

<style>.github-emoji { position: relative; display: inline-block; width: 1.2em; min-height: 1.2em; overflow: hidden; vertical-align: top; color: transparent; }  .github-emoji > span { position: relative; z-index: 10; }  .github-emoji img, .github-emoji .fancybox { margin: 0 !important; padding: 0 !important; border: none !important; outline: none !important; text-decoration: none !important; user-select: none !important; cursor: auto !important; }  .github-emoji img { height: 1.2em !important; width: 1.2em !important; position: absolute !important; left: 50% !important; top: 50% !important; transform: translate(-50%, -50%) !important; user-select: none !important; cursor: auto !important; } .github-emoji-fallback { color: inherit; } .github-emoji-fallback img { opacity: 0 !important; }</style>
<link rel="alternate" href="/atom.xml" title="小四儿" type="application/atom+xml">
<link rel="alternate" href="/rss2.xml" title="小四儿" type="application/rss+xml"><!-- hexo-inject:begin --><!-- hexo-inject:end -->
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <!-- hexo-inject:begin --><!-- hexo-inject:end --><div class="headband"></div>

  <main class="main">
    <div class="column">
      <header class="header" itemscope itemtype="http://schema.org/WPHeader"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <p class="site-title">小四儿</p>
      <i class="logo-line"></i>
    </a>
      <p class="site-subtitle" itemprop="description">心之所愿，无所不至！</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger" aria-label="搜索" role="button">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu"><li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a></li><li class="menu-item menu-item-tags"><a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签<span class="badge">61</span></a></li><li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类<span class="badge">25</span></a></li><li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档<span class="badge">149</span></a></li><li class="menu-item menu-item-welfare"><a href="/welfare" rel="section"><i class="fa fa-star fa-fw"></i>收藏</a></li><li class="menu-item menu-item-music"><a href="/music" rel="section"><i class="fa fa-music fa-fw"></i>音乐</a></li><li class="menu-item menu-item-photos"><a href="/photos" rel="section"><i class="fa fa-camera-retro fa-fw"></i>相册</a></li><li class="menu-item menu-item-links"><a href="/links" rel="section"><i class="fa fa-link fa-fw"></i>友链</a></li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
      <div class="search-header">
        <span class="search-icon">
          <i class="fa fa-search"></i>
        </span>
        <div class="search-input-container">
          <input autocomplete="off" autocapitalize="off" maxlength="80"
                placeholder="搜索..." spellcheck="false"
                type="search" class="search-input">
        </div>
        <span class="popup-btn-close" role="button">
          <i class="fa fa-times-circle"></i>
        </span>
      </div>
      <div class="search-result-container">
        <div class="search-result-icon">
          <i class="fa fa-spinner fa-pulse fa-5x"></i>
        </div>
      </div>
    </div>
  </div>

</header>
        
  
  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#Docker%E5%AE%B9%E5%99%A8%E7%BD%91%E7%BB%9C"><span class="nav-number">1.</span> <span class="nav-text">Docker容器网络</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#Docker%E7%9A%844%E7%A7%8D%E7%BD%91%E7%BB%9C%E6%A8%A1%E5%BC%8F"><span class="nav-number">1.1.</span> <span class="nav-text">Docker的4种网络模式</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#bridge%E6%A8%A1%E5%BC%8F"><span class="nav-number">1.1.1.</span> <span class="nav-text">bridge模式</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#container%E6%A8%A1%E5%BC%8F"><span class="nav-number">1.1.2.</span> <span class="nav-text">container模式</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#host%E6%A8%A1%E5%BC%8F"><span class="nav-number">1.1.3.</span> <span class="nav-text">host模式</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#none%E6%A8%A1%E5%BC%8F"><span class="nav-number">1.1.4.</span> <span class="nav-text">none模式</span></a></li></ol></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#docker%E5%AE%B9%E5%99%A8%E7%BD%91%E7%BB%9C%E9%85%8D%E7%BD%AE"><span class="nav-number">2.</span> <span class="nav-text">docker容器网络配置</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#Linux%E5%86%85%E6%A0%B8%E5%AE%9E%E7%8E%B0%E5%90%8D%E7%A7%B0%E7%A9%BA%E9%97%B4%E7%9A%84%E5%88%9B%E5%BB%BA"><span class="nav-number">2.1.</span> <span class="nav-text">Linux内核实现名称空间的创建</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#ip-netns%E5%91%BD%E4%BB%A4"><span class="nav-number">2.1.1.</span> <span class="nav-text">ip netns命令</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#%E5%88%9B%E5%BB%BANetwork-Namespace"><span class="nav-number">2.1.2.</span> <span class="nav-text">创建Network Namespace</span></a></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E6%93%8D%E4%BD%9CNetwork-Namespace"><span class="nav-number">2.2.</span> <span class="nav-text">操作Network Namespace</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#%E8%BD%AC%E7%A7%BB%E8%AE%BE%E5%A4%87"><span class="nav-number">2.2.1.</span> <span class="nav-text">转移设备</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#veth-pair"><span class="nav-number">2.2.2.</span> <span class="nav-text">veth pair</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#%E5%88%9B%E5%BB%BAveth-pair"><span class="nav-number">2.2.3.</span> <span class="nav-text">创建veth pair</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#%E5%AE%9E%E7%8E%B0Network-Namespace%E9%97%B4%E9%80%9A%E4%BF%A1"><span class="nav-number">2.2.4.</span> <span class="nav-text">实现Network Namespace间通信</span></a></li></ol></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%9B%9B%E7%A7%8D%E7%BD%91%E7%BB%9C%E6%A8%A1%E5%BC%8F%E9%85%8D%E7%BD%AE"><span class="nav-number">3.</span> <span class="nav-text">四种网络模式配置</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#bridge%E6%A8%A1%E5%BC%8F%E9%85%8D%E7%BD%AE"><span class="nav-number">3.1.</span> <span class="nav-text">bridge模式配置</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#none%E6%A8%A1%E5%BC%8F%E9%85%8D%E7%BD%AE"><span class="nav-number">3.2.</span> <span class="nav-text">none模式配置</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#container%E6%A8%A1%E5%BC%8F%E9%85%8D%E7%BD%AE"><span class="nav-number">3.3.</span> <span class="nav-text">container模式配置</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#host%E6%A8%A1%E5%BC%8F%E9%85%8D%E7%BD%AE"><span class="nav-number">3.4.</span> <span class="nav-text">host模式配置</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%AE%B9%E5%99%A8%E7%9A%84%E5%B8%B8%E7%94%A8%E6%93%8D%E4%BD%9C"><span class="nav-number">4.</span> <span class="nav-text">容器的常用操作</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E6%9F%A5%E7%9C%8B%E5%AE%B9%E5%99%A8%E7%9A%84%E4%B8%BB%E6%9C%BA%E5%90%8D"><span class="nav-number">4.1.</span> <span class="nav-text">查看容器的主机名</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#%E5%9C%A8%E5%AE%B9%E5%99%A8%E5%90%AF%E5%8A%A8%E6%97%B6%E6%B3%A8%E5%85%A5%E4%B8%BB%E6%9C%BA%E5%90%8D"><span class="nav-number">4.1.1.</span> <span class="nav-text">在容器启动时注入主机名</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#%E6%89%8B%E5%8A%A8%E6%8C%87%E5%AE%9A%E5%AE%B9%E5%99%A8%E8%A6%81%E4%BD%BF%E7%94%A8%E7%9A%84DNS"><span class="nav-number">4.1.2.</span> <span class="nav-text">手动指定容器要使用的DNS</span></a></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E6%89%8B%E5%8A%A8%E5%BE%80-etc-hosts%E6%96%87%E4%BB%B6%E4%B8%AD%E6%B3%A8%E5%85%A5%E4%B8%BB%E6%9C%BA%E5%90%8D%E5%88%B0IP%E5%9C%B0%E5%9D%80%E7%9A%84%E6%98%A0%E5%B0%84"><span class="nav-number">4.2.</span> <span class="nav-text">手动往&#x2F;etc&#x2F;hosts文件中注入主机名到IP地址的映射</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%BC%80%E6%94%BE%E5%AE%B9%E5%99%A8%E7%AB%AF%E5%8F%A3"><span class="nav-number">5.</span> <span class="nav-text">开放容器端口</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E8%87%AA%E5%AE%9A%E4%B9%89docker0%E6%A1%A5%E7%9A%84%E7%BD%91%E7%BB%9C%E5%B1%9E%E6%80%A7%E4%BF%A1%E6%81%AF"><span class="nav-number">6.</span> <span class="nav-text">自定义docker0桥的网络属性信息</span></a></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="leeze"
      src="https://static.xiaosige.com/img/avatar/avatar.jpg">
  <p class="site-author-name" itemprop="name">leeze</p>
  <div class="site-description" itemprop="description">因上努力，果上随缘！</div>
</div>
<div class="site-state-wrap animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/archives/">
          <span class="site-state-item-count">149</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
          <a href="/categories/">
        <span class="site-state-item-count">25</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
          <a href="/tags/">
        <span class="site-state-item-count">61</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author animated">
      <span class="links-of-author-item">
        <a href="https://github.com/leeze2012" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;leeze2012" rel="noopener me" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="https://www.teambition.com/" title="Teambition → https:&#x2F;&#x2F;www.teambition.com" rel="noopener me" target="_blank"><i class="fab fa-mixcloud fa-fw"></i>Teambition</a>
      </span>
      <span class="links-of-author-item">
        <a href="https://gitee.com/leeze" title="Gitee → https:&#x2F;&#x2F;gitee.com&#x2F;leeze" rel="noopener me" target="_blank"><i class="fab fa-gg fa-fw"></i>Gitee</a>
      </span>
      <span class="links-of-author-item">
        <a href="https://www.jianshu.com/u/e4c5daf92fa6" title="简书 → https:&#x2F;&#x2F;www.jianshu.com&#x2F;u&#x2F;e4c5daf92fa6" rel="noopener me" target="_blank"><i class="fab fa-telegram fa-fw"></i>简书</a>
      </span>
      <span class="links-of-author-item">
        <a href="https://codeup.aliyun.com/" title="Codeup → https:&#x2F;&#x2F;codeup.aliyun.com" rel="noopener me" target="_blank"><i class="fab fa-envira fa-fw"></i>Codeup</a>
      </span>
      <span class="links-of-author-item">
        <a href="https://blog.csdn.net/lileeze" title="CSDN → https:&#x2F;&#x2F;blog.csdn.net&#x2F;lileeze" rel="noopener me" target="_blank"><i class="fa fa-crosshairs fa-fw"></i>CSDN</a>
      </span>
      <span class="links-of-author-item">
        <a href="https://dev.tencent.com/u/leeze" title="腾讯云 → https:&#x2F;&#x2F;dev.tencent.com&#x2F;u&#x2F;leeze" rel="noopener me" target="_blank"><i class="fab fa-jsfiddle fa-fw"></i>腾讯云</a>
      </span>
      <span class="links-of-author-item">
        <a href="https://www.upyun.com/" title="又拍云 → https:&#x2F;&#x2F;www.upyun.com" rel="noopener me" target="_blank"><i class="fab fa-jsfiddle fa-fw"></i>又拍云</a>
      </span>
  </div>

<div class="site-overview-item animated" style="height:140px;">
    <div class="wrap">
        <div class="cup">
            <div class="cup__mouse"></div>
            <div class="cup__eyes"></div>
            <div class="cup__label">多喝水</div>
        </div>
        <div class="cup-shadow"></div>
    </div>
</div>

<style>

.wrap {
  width: 210px;
  height: 90px;
  -webkit-transform: translate(-50%, 50%);
          transform: translate(-50%, 50%);
  position: relative;
  left: 40%;
  /*top: 20%;*/
}

.cup {
  width: 140px;
  height: 100px;
  background: #FFF;
  box-shadow: inset 0px -10px 0 0 #EDDFE6;
  border-radius: 5px 5px 50px 50px;
  -webkit-transform-origin: bottom center;
          transform-origin: bottom center;
  -webkit-animation: .6s linear 0s infinite alternate cup;
          animation: .6s linear 0s infinite alternate cup;
  border: 3px solid #000;
  position: absolute;
  bottom: 0;
  left: 40px;
  z-index: 2;
}
.cup::before {
  content: '';
  width: 140px;
  background: #91ECED;
  height: 40px;
  border-radius: 100%;
  border: 3px solid #000;
  box-shadow: inset 0 20px 0 0 #fff;
  -webkit-animation: .6s linear 0s infinite alternate water;
          animation: .6s linear 0s infinite alternate water;
  position: absolute;
  top: -20px;
  left: -3px;
}
.cup::after {
  content: '';
  width: 22px;
  height: 26px;
  background: transparent;
  border-radius: 30% 100% 100% 30%;
  border: 3px solid #000;
  border-left: none;
  box-shadow: 4px 0 0 9px #fff, 6px 0 0 10px #000;
  position: absolute;
  bottom: 35px;
  right: -20px;
}
.cup__mouse {
  top: 45px;
  left: 45px;
  position: absolute;
  height: 30px;
  width: 50px;
  border: 3px solid #000;
  border-radius: 50%;
  -webkit-clip-path: polygon(50% 10%, 91% 100%, 5% 100%);
          clip-path: polygon(50% 10%, 91% 100%, 5% 100%);
}
.cup__eyes {
  width: 15px;
  height: 15px;
  background: #000;
  border-radius: 50%;
  box-shadow: 58px 0 0 0 #000;
  position: absolute;
  top: 55px;
  left: 35px;
}
.cup__label {
  width: 48px;
  height: 35px;
  box-sizing: content-box;
  /*padding-top: 10px;*/
  background: #ff7600;
  border: 2px solid #000;
  border-bottom: none;
  -webkit-transform-origin: top center;
          transform-origin: top center;
  -webkit-animation: .6s linear 0s infinite alternate label;
          animation: .6s linear 0s infinite alternate label;
  position: absolute;
  top: 40px;
  left: 45px;
  color: #fff
}
.cup__label::before {
  content: '';
  width: 3px;
  height: 15px;
  background: #000;
  -webkit-animation: .6s linear 0s infinite alternate label-line;
          animation: .6s linear 0s infinite alternate label-line;
  position: absolute;
  left: 25px;
  top: -16px;
}
.cup__label::after {
  content: '';
  position: absolute;
  left: -1px;
  bottom: 0;
  width: 0;
  height: 0;
  -webkit-filter: drop-shadow(0 -2px 0 black);
          filter: drop-shadow(0 -2px 0 black);
  border-bottom: 7px solid #fff;
  border-left: 26px solid transparent;
  border-right: 26px solid transparent;
}

.cup-shadow {
  width: 135px;
  height: 90px;
  background: #7CE589;
  border-radius: 40% 40% 100% 100%;
  -webkit-transform-origin: bottom center;
          transform-origin: bottom center;
  -webkit-animation: .6s linear 0s infinite alternate shadow;
          animation: .6s linear 0s infinite alternate shadow;
  position: absolute;
  bottom: -16px;
  left: 55px;
  z-index: 1;
}
.cup-shadow::after {
  content: '';
  width: 20px;
  height: 25px;
  background: transparent;
  border-radius: 30% 100% 100% 30%;
  border-left: none;
  box-shadow: 5px 0 0 5px #7CE589;
  position: absolute;
  bottom: 35px;
  right: -10px;
}

@-webkit-keyframes cup {
  0% {
    -webkit-transform: rotate(10deg);
            transform: rotate(10deg);
    box-shadow: inset -10px -10px 0 0 #EDDFE6;
  }
  100% {
    -webkit-transform: rotate(-10deg);
            transform: rotate(-10deg);
    box-shadow: inset 10px -10px 0 0 #EDDFE6;
  }
}

@keyframes cup {
  0% {
    -webkit-transform: rotate(10deg);
            transform: rotate(10deg);
    box-shadow: inset -10px -10px 0 0 #EDDFE6;
  }
  100% {
    -webkit-transform: rotate(-10deg);
            transform: rotate(-10deg);
    box-shadow: inset 10px -10px 0 0 #EDDFE6;
  }
}
@-webkit-keyframes water {
  0% {
    box-shadow: inset 30px 20px 0 0 #fff;
  }
  100% {
    box-shadow: inset -30px 20px 0 0 #fff;
  }
}
@keyframes water {
  0% {
    box-shadow: inset 30px 20px 0 0 #fff;
  }
  100% {
    box-shadow: inset -30px 20px 0 0 #fff;
  }
}
@-webkit-keyframes label {
  0% {
    -webkit-transform: rotate(40deg);
            transform: rotate(40deg);
  }
  100% {
    -webkit-transform: rotate(-40deg);
            transform: rotate(-40deg);
  }
}
@keyframes label {
  0% {
    -webkit-transform: rotate(40deg);
            transform: rotate(40deg);
  }
  100% {
    -webkit-transform: rotate(-40deg);
            transform: rotate(-40deg);
  }
}
@-webkit-keyframes label-line {
  0% {
    height: 15px;
    top: -16px;
  }
  25% {
    height: 22px;
    top: -22px;
  }
  50% {
    height: 15px;
    top: -16px;
  }
  100% {
    height: 22px;
    top: -22px;
  }
}
@keyframes label-line {
  0% {
    height: 15px;
    top: -16px;
  }
  25% {
    height: 22px;
    top: -22px;
  }
  50% {
    height: 15px;
    top: -16px;
  }
  100% {
    height: 22px;
    top: -22px;
  }
}
@-webkit-keyframes shadow {
  0% {
    -webkit-transform: skewX(-10deg);
            transform: skewX(-10deg);
  }
  100% {
    -webkit-transform: skewX(20deg);
            transform: skewX(20deg);
  }
}
@keyframes shadow {
  0% {
    -webkit-transform: skewX(-10deg);
            transform: skewX(-10deg);
  }
  100% {
    -webkit-transform: skewX(20deg);
            transform: skewX(20deg);
  }
}

.sidebar-panel{
    min-height: calc(var(--sidebar-wrapper-height) * 0.75);
}
.sidebar-toc-active .post-toc-wrap,
.sidebar-overview-active .site-overview-wrap {
  display: block;
}
</style>




<script src="/zone/js/canvasTime.js" async></script>
<div style="display:none;">
  <canvas id="canvas" style="width:60%;">当前浏览器不支持canvas，请更换浏览器后再试</canvas>
</div>
<style>
// 粒子时钟样式
.site-overview {
  text-align: center;
}

canvas#canvas {
  margin-top: 70px;
}
</style>


<div class="site-overview-item animated">
    <div style="">
        <iframe id="sjFrame" loading="lazy" src="/zone/tool/sj/index.html" border="0" width="100%" height="100" frameborder="no"> </iframe>
    </div>
</div>

        </div>
      </div>
    </div>

    
        <div class="pjax">
        </div>
  </aside>


    </div>

    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://www.xiaosige.com/post/2f93af4e.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="https://static.xiaosige.com/img/avatar/avatar.jpg">
      <meta itemprop="name" content="leeze">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="小四儿">
      <meta itemprop="description" content="因上努力，果上随缘！">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="Docker容器网络和Docker容器网络配置 | 小四儿">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          Docker容器网络和Docker容器网络配置
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2021-10-11 21:20:11" itemprop="dateCreated datePublished" datetime="2021-10-11T21:20:11+08:00">2021-10-11</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar-check"></i>
      </span>
      <span class="post-meta-item-text">更新于</span>
      <time title="修改时间：2022-10-12 00:32:20" itemprop="dateModified" datetime="2022-10-12T00:32:20+08:00">2022-10-12</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/Docker/" itemprop="url" rel="index"><span itemprop="name">Docker</span></a>
        </span>
    </span>

  
    <span class="post-meta-item" title="阅读次数" id="busuanzi_container_page_pv">
      <span class="post-meta-item-icon">
        <i class="fa fa-eye"></i>
      </span>
      <span class="post-meta-item-text">阅读次数：</span>
      <span id="busuanzi_value_page_pv"></span>
    </span>



    <span class="post-meta-break"></span>
    <span class="post-meta-item" title="本文字数">
      <span class="post-meta-item-icon">
        <i class="far fa-file-word"></i>
      </span>
      <span class="post-meta-item-text">本文字数：</span>
      <span>19k</span>
    </span>
    <span class="post-meta-item" title="阅读时长">
      <span class="post-meta-item-icon">
        <i class="far fa-clock"></i>
      </span>
      <span class="post-meta-item-text">阅读时长 &asymp;</span>
      <span>17 分钟</span>
    </span>
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody"><img data-src="/post/2f93af4e/dockernw001.png" style="height:260px;width:100%;box-shadow:none!important;">

<span id="more"></span>

<h3 id="Docker容器网络"><a href="#Docker容器网络" class="headerlink" title="Docker容器网络"></a>Docker容器网络</h3><p>  Docker在安装后自动提供3种网络，可以使用<code>docker network ls</code>命令查看</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token punctuation">[</span>root@anolis containers<span class="token punctuation">]</span><span class="token comment"># docker network ls</span>
NETWORK ID     NAME          DRIVER    SCOPE
26f3662e2a00   bridge        bridge    <span class="token builtin class-name">local</span>
24be6b7fd7f8   docker1       bridge    <span class="token builtin class-name">local</span>
fc16af4c2af2   <span class="token function">host</span>          <span class="token function">host</span>      <span class="token builtin class-name">local</span>
ade5dbee404b   nginx-proxy   bridge    <span class="token builtin class-name">local</span>
fe9fd94c0987   none          null      <span class="token builtin class-name">local</span>
56305c516afe   traefik       bridge    <span class="token builtin class-name">local</span>
<span class="token punctuation">[</span>root@anolis containers<span class="token punctuation">]</span><span class="token comment"># </span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>  Docker使用Linux桥接，在宿主机虚拟一个Docker容器网桥(<code>docker0</code>)，Docker启动一个容器时会根据Docker网桥的网段分配给<code>容</code>器一个<code>IP地址</code>，称为<code>Container-IP</code>，同时Docker网桥是每个容器的默认网关。因为在同一宿主机内的容器都接入同一个网桥，这样容器之间就能够通过容器的Container-IP直接通信。</p>
<h4 id="Docker的4种网络模式"><a href="#Docker的4种网络模式" class="headerlink" title="Docker的4种网络模式"></a>Docker的<code>4</code>种网络模式</h4><table>
<thead>
<tr>
<th style="text-align:left">网络模式</th>
<th style="text-align:left">配置</th>
<th style="text-align:left">说明</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:left">host</td>
<td style="text-align:left">–network host</td>
<td style="text-align:left">容器和宿主机共享Network namespace</td>
</tr>
<tr>
<td style="text-align:left">container</td>
<td style="text-align:left">–network container:NAME_OR_ID</td>
<td style="text-align:left">容器和另外一个容器共享Network namespace</td>
</tr>
<tr>
<td style="text-align:left">none</td>
<td style="text-align:left">–network none</td>
<td style="text-align:left">容器有独立的Network namespace，但并没有对其进行任何网络设置，如分配veth pair 和网桥连接，配置IP等</td>
</tr>
<tr>
<td style="text-align:left">bridge</td>
<td style="text-align:left">–network</td>
<td style="text-align:left">bridge 默认模式</td>
</tr>
</tbody>
</table>
<img data-src="/post/2f93af4e/dockernw002.png" class="" title="Network">




<h5 id="bridge模式"><a href="#bridge模式" class="headerlink" title="bridge模式"></a>bridge模式</h5><div class="note success no-icon"><p>  当Docker进程启动时，会在主机上创建一个名为<code>docker0</code>的虚拟网桥，此主机上启动的Docker容器会连接到这个虚拟网桥上。虚拟网桥的工作方式和物理交换机类似，这样主机上的所有容器就通过交换机连在了一个二层网络中。</p>
<p>  从<code>docker0</code>子网中分配一个IP给容器使用，并设置<code>docker0</code>的<code>IP地址</code>为容器的<code>默认网关</code>。在主机上创建一对虚拟网卡<code>veth pair</code>设备，Docker将veth pair设备的一端放在新创建的容器中，并命名为<code>eth0</code>（容器的网卡），另一端放在主机中，以<code>vethxxx</code>这样类似的名字命名，并将这个网络设备加入到<code>docker0</code>网桥中。可以通过<code>brctl show</code>命令查看。</p>
<p>  bridge模式是docker的默认网络模式，不写<code>–network</code>参数，就是bridge模式。使用<code>docker run -p</code>时，docker实际是在iptables做了DNAT规则，实现端口转发功能。可以使用<code>iptables -t nat -vnL</code>查看。</p>
</div>

<p>  bridge模式如下图所示：<br><img data-src="/post/2f93af4e/dockernw003.png" style="height:360px;box-shadow:none!important;"></p>
<p>  假设上图的<code>docker2</code>中运行了一个<code>nginx</code>，大家来想几个问题：</p>
<div class="note info no-icon"><ul>
<li>同主机间两个容器间是否可以直接通信？比如在docker1上能不能直接访问到docker2的nginx站点？</li>
<li>在宿主机上能否直接访问到docker2的nginx站点？</li>
<li>在另一台主机上如何访问node1上的这个nginx站点呢？DNAT发布？</li>
</ul>
</div>
<p>  Docker网桥是宿主机虚拟出来的，并不是真实存在的网络设备，外部网络是无法寻址到的，这也意味着外部网络无法通过直接Container-IP访问到容器。如果容器希望外部访问能够访问到，可以通过映射容器端口到宿主主机（端口映射），即<code>docker run</code>创建容器时候通过 <code>-p</code> 或 <code>-P</code> 参数来启用，访问容器的时候就通过<code>[宿主机IP]</code>:<code>[容器端口]</code>访问容器。</p>
<h5 id="container模式"><a href="#container模式" class="headerlink" title="container模式"></a>container模式</h5><p>  这个模式指定新创建的容器和已经存在的一个<code>容器共享</code>一个 <code>Network Namespace</code>，而不是和宿主机共享。新创建的容器不会创建自己的网卡，配置自己的 IP，而是和一个指定的容器共享 IP、端口范围等。同样，两个容器除了网络方面，其他的如文件系统、进程列表等还是隔离的。两个容器的进程可以通过 <code>lo</code> 网卡设备通信。<br>  container模式如下图所示：</p>
<img data-src="/post/2f93af4e/dockernw004.png" class="" title="container">



<h5 id="host模式"><a href="#host模式" class="headerlink" title="host模式"></a>host模式</h5><p>  如果启动容器的时候使用host模式，那么这个容器将<code>不会</code>获得一个独立的<code>Network Namespace</code>，而是和<code>宿主机共用</code>一个<code>Network Namespace</code>。容器将不会虚拟出自己的网卡，配置自己的IP等，而是使用宿主机的IP和端口。但是，容器的其他方面，如文件系统、进程列表等还是和宿主机隔离的。<br>  使用host模式的容器可以直接使用宿主机的IP地址与外界通信，容器内部的服务端口也可以使用宿主机的端口，不需要进行NAT，host最大的优势就是网络性能比较好，但是<code>docker host</code>上<code>已经</code>使用的<code>端口</code>就<code>不能</code>再用了，网络的隔离性不好。<br>  Host模式如下图所示：<br><img data-src="/post/2f93af4e/dockernw005.png" style="height:360px;box-shadow:none!important;"></p>
<h5 id="none模式"><a href="#none模式" class="headerlink" title="none模式"></a>none模式</h5><p>  使用none模式，Docker容器<code>拥有</code>自己的<code>Network Namespace</code>，但是，并<code>不</code>为Docker容器进行任何<code>网络配置</code>。也就是说，这个Docker容器<code>没有</code>网卡、IP、路由等信息。需要我们自己为Docker容器添加网卡、配置IP等。<br>  这种网络模式下容器只有lo回环网络，没有其他网卡。none模式可以在容器创建时通过–network none来指定。这种类型的网络没有办法联网，封闭的网络能很好的保证容器的安全性。</p>
<p>  应用场景：</p>
<div class="note info no-icon"><ul>
<li>启动一个容器处理数据，比如转换数据格式</li>
<li>一些后台的计算和处理任务</li>
</ul>
</div>

<p>  none模式如下图所示：<br><img data-src="/post/2f93af4e/dockernw006.png" style="height:360px;box-shadow:none!important;"></p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token comment"># 查看bridge网络的详细配置</span>
root@localhost:~<span class="token comment"># docker network inspect bridge</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>



<h3 id="docker容器网络配置"><a href="#docker容器网络配置" class="headerlink" title="docker容器网络配置"></a>docker容器网络配置</h3><h4 id="Linux内核实现名称空间的创建"><a href="#Linux内核实现名称空间的创建" class="headerlink" title="Linux内核实现名称空间的创建"></a>Linux内核实现名称空间的创建</h4><h5 id="ip-netns命令"><a href="#ip-netns命令" class="headerlink" title="ip netns命令"></a><code>ip netns</code>命令</h5><p>  可以借助<code>ip netns</code>命令来完成对 <code>Network Namespace</code> 的各种操作。ip netns命令来自于<code>iproute</code>安装包，一般系统会默认安装，如果没有的话，请自行安装。</p>
<p><code>注意：ip netns命令修改网络配置时需要 sudo 权限。</code></p>
<p>  可以通过ip netns命令完成对Network Namespace 的相关操作，可以通过ip netns help查看命令帮助信息：</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash">root@localhost:~<span class="token comment"># ip netns help</span>
Usage:  <span class="token function">ip</span> netns list
        <span class="token function">ip</span> netns <span class="token function">add</span> NAME
        <span class="token function">ip</span> netns attach NAME PID
        <span class="token function">ip</span> netns <span class="token builtin class-name">set</span> NAME NETNSID
        <span class="token function">ip</span> <span class="token punctuation">[</span>-all<span class="token punctuation">]</span> netns delete <span class="token punctuation">[</span>NAME<span class="token punctuation">]</span>
        <span class="token function">ip</span> netns identify <span class="token punctuation">[</span>PID<span class="token punctuation">]</span>
        <span class="token function">ip</span> netns pids NAME
        <span class="token function">ip</span> <span class="token punctuation">[</span>-all<span class="token punctuation">]</span> netns <span class="token builtin class-name">exec</span> <span class="token punctuation">[</span>NAME<span class="token punctuation">]</span> cmd <span class="token punctuation">..</span>.
        <span class="token function">ip</span> netns monitor
        <span class="token function">ip</span> netns list-id <span class="token punctuation">[</span>target-nsid POSITIVE-INT<span class="token punctuation">]</span> <span class="token punctuation">[</span>nsid POSITIVE-INT<span class="token punctuation">]</span>
NETNSID :<span class="token operator">=</span> auto <span class="token operator">|</span> POSITIVE-INT
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>  默认情况下，Linux系统中是没有任何 <code>Network Namespace</code>的，所以<code>ip netns list</code>命令不会返回任何信息。</p>
<h5 id="创建Network-Namespace"><a href="#创建Network-Namespace" class="headerlink" title="创建Network Namespace"></a>创建Network Namespace</h5><p>  通过命令创建一个名为<code>ns0</code>的命名空间：</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash">root@localhost:~<span class="token comment"># ip netns list</span>
root@localhost:~<span class="token comment"># ip netns add ns0</span>
root@localhost:~<span class="token comment"># ip netns list</span>
ns0
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>
<p>  新创建的 <code>Network Namespace</code> 会出现在<code>/var/run/netns/</code>目录下。如果相同名字的 namespace 已经存在，命令会报Cannot create namespace file “/var/run/netns/ns0”: File exists的错误。</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash">root@localhost:~<span class="token comment"># ls /var/run/netns/</span>
ns0
root@localhost:~<span class="token comment"># ip netns add ns0</span>
Cannot create namespace <span class="token function">file</span> <span class="token string">"/var/run/netns/ns0"</span><span class="token builtin class-name">:</span> File exists
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>
<p>  对于每个 Network Namespace 来说，它会有自己独立的网卡、路由表、ARP 表、iptables 等和网络相关的资源。</p>
<h4 id="操作Network-Namespace"><a href="#操作Network-Namespace" class="headerlink" title="操作Network Namespace"></a>操作Network Namespace</h4><p>  ip命令提供了<code>ip netns exec</code>子命令可以在对应的 Network Namespace 中执行命令。<br>  查看新创建 Network Namespace 的网卡信息</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash">root@localhost:~<span class="token comment"># ip netns exec ns0 ip addr</span>
<span class="token number">1</span>: lo: <span class="token operator">&lt;</span>LOOPBACK<span class="token operator">&gt;</span> mtu <span class="token number">65536</span> qdisc noop state DOWN group default qlen <span class="token number">1000</span>
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>
<p>  可以看到，新创建的Network Namespace中会默认创建一个lo回环网卡，此时网卡处于关闭状态。此时，尝试去 ping 该lo回环网卡，会提示Network is unreachable</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token comment"># 127.0.0.1是默认回环网卡</span>
root@localhost:~<span class="token comment"># ip netns exec ns0 ping 127.0.0.1</span>
ping: connect: Network is unreachable
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>
<p>  通过下面的命令启用lo回环网卡：</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash">root@localhost:~<span class="token comment"># ip netns exec ns0 ip link set lo up</span>
root@localhost:~<span class="token comment"># ip netns exec ns0 ping 127.0.0.1</span>
PING <span class="token number">127.0</span>.0.1 <span class="token punctuation">(</span><span class="token number">127.0</span>.0.1<span class="token punctuation">)</span> <span class="token number">56</span><span class="token punctuation">(</span><span class="token number">84</span><span class="token punctuation">)</span> bytes of data.
<span class="token number">64</span> bytes from <span class="token number">127.0</span>.0.1: <span class="token assign-left variable">icmp_seq</span><span class="token operator">=</span><span class="token number">1</span> <span class="token assign-left variable">ttl</span><span class="token operator">=</span><span class="token number">64</span> <span class="token assign-left variable">time</span><span class="token operator">=</span><span class="token number">0.051</span> ms
<span class="token number">64</span> bytes from <span class="token number">127.0</span>.0.1: <span class="token assign-left variable">icmp_seq</span><span class="token operator">=</span><span class="token number">2</span> <span class="token assign-left variable">ttl</span><span class="token operator">=</span><span class="token number">64</span> <span class="token assign-left variable">time</span><span class="token operator">=</span><span class="token number">0.066</span> ms
<span class="token number">64</span> bytes from <span class="token number">127.0</span>.0.1: <span class="token assign-left variable">icmp_seq</span><span class="token operator">=</span><span class="token number">3</span> <span class="token assign-left variable">ttl</span><span class="token operator">=</span><span class="token number">64</span> <span class="token assign-left variable">time</span><span class="token operator">=</span><span class="token number">0.058</span> ms
^C
--- <span class="token number">127.0</span>.0.1 <span class="token function">ping</span> statistics ---
<span class="token number">6</span> packets transmitted, <span class="token number">6</span> received, <span class="token number">0</span>% packet loss, <span class="token function">time</span> 5105ms
rtt min/avg/max/mdev <span class="token operator">=</span> <span class="token number">0.051</span>/0.064/0.077/0.008 ms
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>


<h5 id="转移设备"><a href="#转移设备" class="headerlink" title="转移设备"></a>转移设备</h5><p>  我们可以在不同的 Network Namespace 之间转移设备（如<code>veth</code>）。由于一个设备只能属于一个 Network Namespace ，所以转移后在这个 Network Namespace 内就看不到这个设备了。<br>  其中，<code>veth</code>设备属于可转移设备，而很多其它设备（如lo、vxlan、ppp、bridge等）是不可以转移的。</p>
<h5 id="veth-pair"><a href="#veth-pair" class="headerlink" title="veth pair"></a>veth pair</h5><p>  veth pair 全称是 Virtual Ethernet Pair，是一个成对的端口，所有从这对端口一 端进入的数据包都将从另一端出来，反之也是一样。<br>  引入veth pair是为了在不同的 Network Namespace 直接进行通信，利用它可以直接将两个 Network Namespace 连接起来。</p>
<img data-src="/post/2f93af4e/dockernw007.png" style="height:360px;box-shadow:none!important;">

<h5 id="创建veth-pair"><a href="#创建veth-pair" class="headerlink" title="创建veth pair"></a>创建veth pair</h5><pre class="line-numbers language-bash" data-language="bash"><code class="language-bash">root@localhost:~<span class="token comment"># ip link add type veth</span>
root@localhost:~<span class="token comment"># ip a</span>

<span class="token number">7</span>: veth0@veth1: <span class="token operator">&lt;</span>BROADCAST,MULTICAST,M-DOWN<span class="token operator">&gt;</span> mtu <span class="token number">1500</span> qdisc noop state DOWN group default qlen <span class="token number">1000</span>
    link/ether <span class="token number">86</span>:5c:bb:8e:0f:71 brd ff:ff:ff:ff:ff:ff
<span class="token number">8</span>: veth1@veth0: <span class="token operator">&lt;</span>BROADCAST,MULTICAST,M-DOWN<span class="token operator">&gt;</span> mtu <span class="token number">1500</span> qdisc noop state DOWN group default qlen <span class="token number">1000</span>
    link/ether c2:e3:c6:13:09:50 brd ff:ff:ff:ff:ff:ff
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>  可以看到，此时系统中新增了一对veth pair，将<code>veth0</code>和<code>veth1</code>两个虚拟网卡连接了起来，此时这对 veth pair 处于”未启用“状态。</p>
<h5 id="实现Network-Namespace间通信"><a href="#实现Network-Namespace间通信" class="headerlink" title="实现Network Namespace间通信"></a>实现Network Namespace间通信</h5><p>  下面我们利用<code>veth pair</code>实现两个不同的 Network Namespace 之间的通信。刚才我们已经创建了一个名为<code>ns0</code>的 Network Namespace，下面再创建一个信息Network Namespace，命名为<code>ns1</code></p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash">root@localhost:~<span class="token comment"># ip netns add ns1</span>
root@localhost:~<span class="token comment"># ip netns list</span>
ns1
ns0
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>
<p>  然后我们将<code>veth0</code>加入到<code>ns0</code>，将<code>veth1</code>加入到<code>ns1</code></p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash">root@localhost:~<span class="token comment"># ip link set veth0 netns ns0</span>
root@localhost:~<span class="token comment"># ip link set veth1 netns ns1</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>
<p>  然后我们分别为这对<code>veth pair</code>配置上<code>ip</code>地址，并启用它们</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash">root@localhost:~<span class="token comment"># ip netns exec ns0 ip link set veth0 up</span>
root@localhost:~<span class="token comment"># ip netns exec ns0 ip addr add 192.0.0.1/24 dev veth0</span>
root@localhost:~<span class="token comment"># ip netns exec ns1 ip link set veth1 up</span>
root@localhost:~<span class="token comment"># ip netns exec ns1 ip addr add 192.0.0.2/24 dev veth1</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>
<p>  查看这对<code>veth pair</code>的状态</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash">root@localhost:~<span class="token comment"># ip netns exec ns0 ip a</span>
<span class="token number">1</span>: lo: <span class="token operator">&lt;</span>LOOPBACK,UP,LOWER_UP<span class="token operator">&gt;</span> mtu <span class="token number">65536</span> qdisc noqueue state UNKNOWN group default qlen <span class="token number">1000</span>
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet <span class="token number">127.0</span>.0.1/8 scope <span class="token function">host</span> lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope <span class="token function">host</span> 
       valid_lft forever preferred_lft forever
<span class="token number">4</span>: veth0@if5: <span class="token operator">&lt;</span>BROADCAST,MULTICAST,UP,LOWER_UP<span class="token operator">&gt;</span> mtu <span class="token number">1500</span> qdisc noqueue state UP group default qlen <span class="token number">1000</span>
    link/ether 0a:f4:e2:2d:37:fb brd ff:ff:ff:ff:ff:ff link-netns ns1
    inet <span class="token number">192.0</span>.0.1/24 scope global veth0
       valid_lft forever preferred_lft forever
    inet6 fe80::8f4:e2ff:fe2d:37fb/64 scope <span class="token function">link</span> 
       valid_lft forever preferred_lft forever
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash">root@localhost:~<span class="token comment"># ip netns exec ns1 ip a</span>
<span class="token number">1</span>: lo: <span class="token operator">&lt;</span>LOOPBACK<span class="token operator">&gt;</span> mtu <span class="token number">65536</span> qdisc noop state DOWN group default qlen <span class="token number">1000</span>
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
<span class="token number">5</span>: veth1@if4: <span class="token operator">&lt;</span>BROADCAST,MULTICAST,UP,LOWER_UP<span class="token operator">&gt;</span> mtu <span class="token number">1500</span> qdisc noqueue state UP group default qlen <span class="token number">1000</span>
    link/ether 5e:7e:f6:59:f0:4f brd ff:ff:ff:ff:ff:ff link-netns ns0
    inet <span class="token number">192.0</span>.0.2/24 scope global veth1
       valid_lft forever preferred_lft forever
    inet6 fe80::5c7e:f6ff:fe59:f04f/64 scope <span class="token function">link</span> 
       valid_lft forever preferred_lft forever
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>  从上面可以看出，我们已经成功启用了这个<code>veth pair</code>，并为每个<code>veth</code>设备分配了对应的<code>ip</code>地址。我们尝试在<code>ns1</code>中访问<code>ns0</code>中的ip地址</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash">root@localhost:~<span class="token comment"># ip netns exec ns1 ping 192.0.0.1</span>
PING <span class="token number">192.0</span>.0.1 <span class="token punctuation">(</span><span class="token number">192.0</span>.0.1<span class="token punctuation">)</span> <span class="token number">56</span><span class="token punctuation">(</span><span class="token number">84</span><span class="token punctuation">)</span> bytes of data.
<span class="token number">64</span> bytes from <span class="token number">192.0</span>.0.1: <span class="token assign-left variable">icmp_seq</span><span class="token operator">=</span><span class="token number">1</span> <span class="token assign-left variable">ttl</span><span class="token operator">=</span><span class="token number">64</span> <span class="token assign-left variable">time</span><span class="token operator">=</span><span class="token number">0.033</span> ms
<span class="token number">64</span> bytes from <span class="token number">192.0</span>.0.1: <span class="token assign-left variable">icmp_seq</span><span class="token operator">=</span><span class="token number">2</span> <span class="token assign-left variable">ttl</span><span class="token operator">=</span><span class="token number">64</span> <span class="token assign-left variable">time</span><span class="token operator">=</span><span class="token number">0.041</span> ms
^C
--- <span class="token number">192.0</span>.0.1 <span class="token function">ping</span> statistics ---
<span class="token number">2</span> packets transmitted, <span class="token number">2</span> received, <span class="token number">0</span>% packet loss, <span class="token function">time</span> 1001ms
rtt min/avg/max/mdev <span class="token operator">=</span> <span class="token number">0.033</span>/0.037/0.041/0.004 ms

root@localhost:~<span class="token comment"># ip netns exec ns0 ping 192.0.0.2</span>
PING <span class="token number">192.0</span>.0.2 <span class="token punctuation">(</span><span class="token number">192.0</span>.0.2<span class="token punctuation">)</span> <span class="token number">56</span><span class="token punctuation">(</span><span class="token number">84</span><span class="token punctuation">)</span> bytes of data.
<span class="token number">64</span> bytes from <span class="token number">192.0</span>.0.2: <span class="token assign-left variable">icmp_seq</span><span class="token operator">=</span><span class="token number">1</span> <span class="token assign-left variable">ttl</span><span class="token operator">=</span><span class="token number">64</span> <span class="token assign-left variable">time</span><span class="token operator">=</span><span class="token number">0.025</span> ms
<span class="token number">64</span> bytes from <span class="token number">192.0</span>.0.2: <span class="token assign-left variable">icmp_seq</span><span class="token operator">=</span><span class="token number">2</span> <span class="token assign-left variable">ttl</span><span class="token operator">=</span><span class="token number">64</span> <span class="token assign-left variable">time</span><span class="token operator">=</span><span class="token number">0.025</span> ms
^C
--- <span class="token number">192.0</span>.0.2 <span class="token function">ping</span> statistics ---
<span class="token number">2</span> packets transmitted, <span class="token number">2</span> received, <span class="token number">0</span>% packet loss, <span class="token function">time</span> 1038ms
rtt min/avg/max/mdev <span class="token operator">=</span> <span class="token number">0.025</span>/0.025/0.025/0.000 ms
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>  可以看到，<code>veth pair</code>成功实现了两个不同Network Namespace之间的网络交互。</p>
<h3 id="四种网络模式配置"><a href="#四种网络模式配置" class="headerlink" title="四种网络模式配置"></a>四种网络模式配置</h3><h4 id="bridge模式配置"><a href="#bridge模式配置" class="headerlink" title="bridge模式配置"></a>bridge模式配置</h4><pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token punctuation">[</span>root@localhost ~<span class="token punctuation">]</span><span class="token comment"># docker run -it --name ti --rm busybox</span>
/ <span class="token comment"># ifconfig</span>
eth0      Link encap:Ethernet  HWaddr 02:42:AC:11:00:02  
          inet addr:172.17.0.2  Bcast:172.17.255.255  Mask:255.255.0.0
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:12 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0 
          RX bytes:1032 <span class="token punctuation">(</span><span class="token number">1.0</span> KiB<span class="token punctuation">)</span>  TX bytes:0 <span class="token punctuation">(</span><span class="token number">0.0</span> B<span class="token punctuation">)</span>

lo        Link encap:Local Loopback  
          inet addr:127.0.0.1  Mask:255.0.0.0
          UP LOOPBACK RUNNING  MTU:65536  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000 
          RX bytes:0 <span class="token punctuation">(</span><span class="token number">0.0</span> B<span class="token punctuation">)</span>  TX bytes:0 <span class="token punctuation">(</span><span class="token number">0.0</span> B<span class="token punctuation">)</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>  在创建容器时添加<code>–network bridge</code>与不加<code>–network</code>选项效果是一致的</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"> <span class="token punctuation">[</span>root@localhost ~<span class="token punctuation">]</span><span class="token comment"># docker run -it --name t1 --network bridge --rm busybox</span>
/ <span class="token comment"># ifconfig</span>
eth0      Link encap:Ethernet  HWaddr 02:42:AC:11:00:02  
          inet addr:172.17.0.2  Bcast:172.17.255.255  Mask:255.255.0.0
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:8 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0 
          RX bytes:696 <span class="token punctuation">(</span><span class="token number">696.0</span> B<span class="token punctuation">)</span>  TX bytes:0 <span class="token punctuation">(</span><span class="token number">0.0</span> B<span class="token punctuation">)</span>

lo        Link encap:Local Loopback  
          inet addr:127.0.0.1  Mask:255.0.0.0
          UP LOOPBACK RUNNING  MTU:65536  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000 
          RX bytes:0 <span class="token punctuation">(</span><span class="token number">0.0</span> B<span class="token punctuation">)</span>  TX bytes:0 <span class="token punctuation">(</span><span class="token number">0.0</span> B<span class="token punctuation">)</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h4 id="none模式配置"><a href="#none模式配置" class="headerlink" title="none模式配置"></a>none模式配置</h4><pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token punctuation">[</span>root@localhost ~<span class="token punctuation">]</span><span class="token comment"># docker run -it --name t1 --network none --rm busybox</span>
/ <span class="token comment"># ifconfig -a</span>
lo        Link encap:Local Loopback  
          inet addr:127.0.0.1  Mask:255.0.0.0
          UP LOOPBACK RUNNING  MTU:65536  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000 
          RX bytes:0 <span class="token punctuation">(</span><span class="token number">0.0</span> B<span class="token punctuation">)</span>  TX bytes:0 <span class="token punctuation">(</span><span class="token number">0.0</span> B<span class="token punctuation">)</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h4 id="container模式配置"><a href="#container模式配置" class="headerlink" title="container模式配置"></a>container模式配置</h4><p>  启动第一个容器</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token punctuation">[</span>root@localhost ~<span class="token punctuation">]</span><span class="token comment"># docker run -dit --name b3 busybox</span>
af5ba32f990ebf5a46d7ecaf1eec67f1712bbef6ad7df37d52b7a8a498a592a0

<span class="token punctuation">[</span>root@localhost ~<span class="token punctuation">]</span><span class="token comment"># docker exec -it b3 /bin/sh</span>
/ <span class="token comment"># ifconfig </span>
eth0      Link encap:Ethernet  HWaddr 02:42:AC:11:00:02  
          inet addr:172.17.0.2  Bcast:172.17.255.255  Mask:255.255.0.0
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:11 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0 
          RX bytes:906 <span class="token punctuation">(</span><span class="token number">906.0</span> B<span class="token punctuation">)</span>  TX bytes:0 <span class="token punctuation">(</span><span class="token number">0.0</span> B<span class="token punctuation">)</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>  启动第二个容器</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token punctuation">[</span>root@localhost ~<span class="token punctuation">]</span><span class="token comment"># docker run -it --name b2 --rm busybox</span>
/ <span class="token comment"># ifconfig </span>
eth0      Link encap:Ethernet  HWaddr 02:42:AC:11:00:03  
          inet addr:172.17.0.3  Bcast:172.17.255.255  Mask:255.255.0.0
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:6 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0 
          RX bytes:516 <span class="token punctuation">(</span><span class="token number">516.0</span> B<span class="token punctuation">)</span>  TX bytes:0 <span class="token punctuation">(</span><span class="token number">0.0</span> B<span class="token punctuation">)</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>  可以看到名为b2的容器IP地址是10.0.0.3，与第一个容器的IP地址不是一样的，也就是说并没有共享网络，此时如果我们将第二个容器的启动方式改变一下，就可以使名为b2的容器IP与B3容器IP一致，也即共享IP，但不共享文件系统。</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token punctuation">[</span>root@localhost ~<span class="token punctuation">]</span><span class="token comment"># docker run -it --name b2 --rm --network container:b3 busybox</span>
/ <span class="token comment"># ifconfig </span>
eth0      Link encap:Ethernet  HWaddr 02:42:AC:11:00:02  
          inet addr:172.17.0.2  Bcast:172.17.255.255  Mask:255.255.0.0
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:14 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0 
          RX bytes:1116 <span class="token punctuation">(</span><span class="token number">1.0</span> KiB<span class="token punctuation">)</span>  TX bytes:0 <span class="token punctuation">(</span><span class="token number">0.0</span> B<span class="token punctuation">)</span>

此时我们在b1容器上创建一个目录
/ <span class="token comment"># mkdir /tmp/data</span>
/ <span class="token comment"># ls /tmp</span>
data
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>  到b2容器上检查/tmp目录会发现并没有这个目录，因为文件系统是处于隔离状态，仅仅是共享了网络而已。<br>  在b2容器上部署一个站点</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash">/ <span class="token comment"># echo 'hello world' &gt; /tmp/index.html</span>
/ <span class="token comment"># ls /tmp</span>
index.html
/ <span class="token comment"># httpd -h /tmp</span>
/ <span class="token comment"># netstat -antl</span>
Active Internet connections <span class="token punctuation">(</span>servers and established<span class="token punctuation">)</span>
Proto Recv-Q Send-Q Local Address           Foreign Address         State       
tcp        <span class="token number">0</span>      <span class="token number">0</span> :::80                   :::*                    LISTEN      
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>  在b1容器上用本地地址去访问此站点</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash">/ <span class="token comment"># wget -O - -q 172.17.0.2:80</span>
hello world
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>
<h4 id="host模式配置"><a href="#host模式配置" class="headerlink" title="host模式配置"></a>host模式配置</h4><p>  启动容器时直接指明模式为<code>host</code></p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token punctuation">[</span>root@localhost ~<span class="token punctuation">]</span><span class="token comment"># docker run -it --name b2 --rm --network host busybox</span>
/ <span class="token comment"># ifconfig </span>
docker0   Link encap:Ethernet  HWaddr 02:42:B8:7F:8E:2C  
          inet addr:172.17.0.1  Bcast:172.17.255.255  Mask:255.255.0.0
          inet6 addr: fe80::42:b8ff:fe7f:8e2c/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:3 errors:0 dropped:0 overruns:0 frame:0
          TX packets:20 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0 
          RX bytes:116 <span class="token punctuation">(</span><span class="token number">116.0</span> B<span class="token punctuation">)</span>  TX bytes:1664 <span class="token punctuation">(</span><span class="token number">1.6</span> KiB<span class="token punctuation">)</span>

ens33     Link encap:Ethernet  HWaddr 00:0C:29:95:19:47  
          inet addr:192.168.203.138  Bcast:192.168.203.255  Mask:255.255.255.0
          inet6 addr: fe80::2e61:1ea3:c05a:3d9b/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:9626 errors:0 dropped:0 overruns:0 frame:0
          TX packets:3950 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000 
          RX bytes:3779562 <span class="token punctuation">(</span><span class="token number">3.6</span> MiB<span class="token punctuation">)</span>  TX bytes:362386 <span class="token punctuation">(</span><span class="token number">353.8</span> KiB<span class="token punctuation">)</span>

lo        Link encap:Local Loopback  
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:65536  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000 
          RX bytes:0 <span class="token punctuation">(</span><span class="token number">0.0</span> B<span class="token punctuation">)</span>  TX bytes:0 <span class="token punctuation">(</span><span class="token number">0.0</span> B<span class="token punctuation">)</span>

veth09ee47e Link encap:Ethernet  HWaddr B2:10:53:7B:66:AE  
          inet6 addr: fe80::b010:53ff:fe7b:66ae/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:3 errors:0 dropped:0 overruns:0 frame:0
          TX packets:19 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0 
          RX bytes:158 <span class="token punctuation">(</span><span class="token number">158.0</span> B<span class="token punctuation">)</span>  TX bytes:1394 <span class="token punctuation">(</span><span class="token number">1.3</span> KiB<span class="token punctuation">)</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>  此时如果我们在这个容器中启动一个http站点，我们就可以直接用宿主机的IP直接在浏览器中访问这个容器中的站点了。</p>
<h3 id="容器的常用操作"><a href="#容器的常用操作" class="headerlink" title="容器的常用操作"></a>容器的常用操作</h3><h4 id="查看容器的主机名"><a href="#查看容器的主机名" class="headerlink" title="查看容器的主机名"></a>查看容器的主机名</h4><pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token punctuation">[</span>root@localhost ~<span class="token punctuation">]</span><span class="token comment"># docker run -it --name t1 --network bridge --rm busybox</span>
/ <span class="token comment"># hostname</span>
48cb45a0b2e7
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>
<h5 id="在容器启动时注入主机名"><a href="#在容器启动时注入主机名" class="headerlink" title="在容器启动时注入主机名"></a>在容器启动时注入主机名</h5><pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token punctuation">[</span>root@localhost ~<span class="token punctuation">]</span><span class="token comment"># docker run -it --name t1 --network bridge --hostname ljl --rm busybox</span>
/ <span class="token comment"># hostname </span>
ljl
/ <span class="token comment"># cat /etc/hosts</span>
<span class="token number">127.0</span>.0.1	localhost
::1	localhost ip6-localhost ip6-loopback
fe00::0	ip6-localnet
ff00::0	ip6-mcastprefix
ff02::1	ip6-allnodes
ff02::2	ip6-allrouters
<span class="token number">172.17</span>.0.3	ljl
/ <span class="token comment"># cat /etc/resolv.conf </span>
<span class="token comment"># Generated by NetworkManager</span>
search localdomain
nameserver <span class="token number">192.168</span>.203.2
/ <span class="token comment"># ping www.baidu.com</span>
PING www.baidu.com <span class="token punctuation">(</span><span class="token number">182.61</span>.200.7<span class="token punctuation">)</span>: <span class="token number">56</span> data bytes
<span class="token number">64</span> bytes from <span class="token number">182.61</span>.200.7: <span class="token assign-left variable">seq</span><span class="token operator">=</span><span class="token number">0</span> <span class="token assign-left variable">ttl</span><span class="token operator">=</span><span class="token number">127</span> <span class="token assign-left variable">time</span><span class="token operator">=</span><span class="token number">31.929</span> ms
<span class="token number">64</span> bytes from <span class="token number">182.61</span>.200.7: <span class="token assign-left variable">seq</span><span class="token operator">=</span><span class="token number">1</span> <span class="token assign-left variable">ttl</span><span class="token operator">=</span><span class="token number">127</span> <span class="token assign-left variable">time</span><span class="token operator">=</span><span class="token number">41.062</span> ms
<span class="token number">64</span> bytes from <span class="token number">182.61</span>.200.7: <span class="token assign-left variable">seq</span><span class="token operator">=</span><span class="token number">2</span> <span class="token assign-left variable">ttl</span><span class="token operator">=</span><span class="token number">127</span> <span class="token assign-left variable">time</span><span class="token operator">=</span><span class="token number">31.540</span> ms
^C
--- www.baidu.com <span class="token function">ping</span> statistics ---
<span class="token number">3</span> packets transmitted, <span class="token number">3</span> packets received, <span class="token number">0</span>% packet loss
round-trip min/avg/max <span class="token operator">=</span> <span class="token number">31.540</span>/34.843/41.062 ms
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h5 id="手动指定容器要使用的DNS"><a href="#手动指定容器要使用的DNS" class="headerlink" title="手动指定容器要使用的DNS"></a>手动指定容器要使用的DNS</h5><pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token punctuation">[</span>root@localhost ~<span class="token punctuation">]</span><span class="token comment"># docker run -it --name t1 --network bridge --hostname ljl --dns 114.114.114.114 --rm busybox</span>
/ <span class="token comment"># cat /etc/resolv.conf </span>
search localdomain
nameserver <span class="token number">114.114</span>.114.114
/ <span class="token comment"># nslookup -type=a www.baidu.com</span>
Server:		<span class="token number">114.114</span>.114.114
Address:	<span class="token number">114.114</span>.114.114:53

Non-authoritative answer:
www.baidu.com	canonical name <span class="token operator">=</span> www.a.shifen.com
Name:	www.a.shifen.com
Address: <span class="token number">182.61</span>.200.6
Name:	www.a.shifen.com
Address: <span class="token number">182.61</span>.200.7
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h4 id="手动往-etc-hosts文件中注入主机名到IP地址的映射"><a href="#手动往-etc-hosts文件中注入主机名到IP地址的映射" class="headerlink" title="手动往/etc/hosts文件中注入主机名到IP地址的映射"></a>手动往<code>/etc/hosts</code>文件中注入主机名到IP地址的映射</h4><pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token punctuation">[</span>root@localhost ~<span class="token punctuation">]</span><span class="token comment"># docker run -it --name t1 --network bridge --hostname ljl --add-host www.a.com:1.1.1.1 --rm busybox</span>
/ <span class="token comment"># cat /etc/hosts</span>

<span class="token number">127.0</span>.0.1	localhost
::1	localhost ip6-localhost ip6-loopback
fe00::0	ip6-localnet
ff00::0	ip6-mcastprefix
ff02::1	ip6-allnodes
ff02::2	ip6-allrouters
<span class="token number">1.1</span>.1.1	www.a.com
<span class="token number">172.17</span>.0.3	ljl
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h3 id="开放容器端口"><a href="#开放容器端口" class="headerlink" title="开放容器端口"></a>开放容器端口</h3><p>  执行<code>docker run</code>的时候有个<code>-p</code>选项，可以将容器中的应用端口映射到宿主机中，从而实现让外部主机可以通过访问宿主机的某端口来访问容器内应用的目的。</p>
<p>  <code>-p</code>选项能够使用多次，其所能够暴露的端口必须是容器确实在监听的端口。</p>
<div class="note info no-icon"><blockquote>
<p><code>-p</code>选项的使用格式：</p>
</blockquote>
<ul>
<li><code>-p containerPort</code></li>
<li>将指定的容器端口映射至主机所有地址的一个动态端口</li>
<li><code>-p hostPort : containerPort</code></li>
<li>将容器端口 containerPort 映射至指定的主机端口 hostPort</li>
<li><code>-p ip :: containerPort</code></li>
<li>将指定的容器端口 containerPort 映射至主机指定 ip 的动态端口</li>
<li><code>-p ip : hostPort : containerPort</code></li>
<li>将指定的容器端口 containerPort 映射至主机指定 ip 的端口 hostPort</li>
</ul>
</div>

<p>  动态端口指的是随机端口，具体的映射结果可使用<code>docker port</code>命令查看。</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token punctuation">[</span>root@localhost ~<span class="token punctuation">]</span><span class="token comment"># docker run -dit --name web1 -p 192.168.203.138::80 httpd</span>
e97bc1774e40132659990090f0e98a308a7f83986610ca89037713e9af8a6b9f

<span class="token punctuation">[</span>root@localhost ~<span class="token punctuation">]</span><span class="token comment"># docker ps </span>
CONTAINER ID   IMAGE     COMMAND              CREATED          STATUS          PORTS                           NAMES
e97bc1774e40   httpd     <span class="token string">"httpd-foreground"</span>   <span class="token number">6</span> seconds ago    Up <span class="token number">5</span> seconds    <span class="token number">192.168</span>.203.138:49153-<span class="token operator">&gt;</span><span class="token number">80</span>/tcp   web1
af5ba32f990e   busybox   <span class="token string">"sh"</span>                 <span class="token number">48</span> minutes ago   Up <span class="token number">48</span> minutes                                   b3

<span class="token punctuation">[</span>root@localhost ~<span class="token punctuation">]</span><span class="token comment"># ss -antl</span>
State    Recv-Q   Send-Q        Local Address:Port        Peer Address:Port   Process   
LISTEN   <span class="token number">0</span>        <span class="token number">128</span>         <span class="token number">192.168</span>.203.138:49153            <span class="token number">0.0</span>.0.0:*                
LISTEN   <span class="token number">0</span>        <span class="token number">128</span>                 <span class="token number">0.0</span>.0.0:22               <span class="token number">0.0</span>.0.0:*                
LISTEN   <span class="token number">0</span>        <span class="token number">128</span>                    <span class="token punctuation">[</span>::<span class="token punctuation">]</span>:22                  <span class="token punctuation">[</span>::<span class="token punctuation">]</span>:*       
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>  以上命令执行后会一直占用着前端，我们新开一个终端连接来看一下容器的<code>80</code>端口被映射到了宿主机的什么端口上</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token punctuation">[</span>root@localhost ~<span class="token punctuation">]</span><span class="token comment"># docker port web1</span>
<span class="token number">80</span>/tcp -<span class="token operator">&gt;</span> <span class="token number">192.168</span>.203.138:49153
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>
<p>  由此可见，容器的<code>8</code>0端口被暴露到了宿主机的<code>49153</code>端口上，此时我们在宿主机上访问一下这个端口看是否能访问到容器内的站点</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token punctuation">[</span>root@localhost ~<span class="token punctuation">]</span><span class="token comment"># curl http://192.168.203.138:49153</span>
<span class="token operator">&lt;</span>html<span class="token operator">&gt;</span><span class="token operator">&lt;</span>body<span class="token operator">&gt;</span><span class="token operator">&lt;</span>h<span class="token operator"><span class="token file-descriptor important">1</span>&gt;</span>It works<span class="token operator">!</span><span class="token operator">&lt;</span>/h<span class="token operator"><span class="token file-descriptor important">1</span>&gt;</span><span class="token operator">&lt;</span>/body<span class="token operator">&gt;</span><span class="token operator">&lt;</span>/html<span class="token operator">&gt;</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>
<p>  <code>iptables</code>防火墙规则将随容器的创建自动生成，随容器的删除自动删除规则。</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token punctuation">[</span>root@localhost ~<span class="token punctuation">]</span><span class="token comment"># iptables -t nat -nvL</span>
Chain PREROUTING <span class="token punctuation">(</span>policy ACCEPT <span class="token number">0</span> packets, <span class="token number">0</span> bytes<span class="token punctuation">)</span>
 pkts bytes target     prot opt <span class="token keyword">in</span>     out     <span class="token builtin class-name">source</span>               destination         
    <span class="token number">3</span>   <span class="token number">164</span> DOCKER     all  --  *      *       <span class="token number">0.0</span>.0.0/0            <span class="token number">0.0</span>.0.0/0            ADDRTYPE match dst-type LOCAL

Chain INPUT <span class="token punctuation">(</span>policy ACCEPT <span class="token number">0</span> packets, <span class="token number">0</span> bytes<span class="token punctuation">)</span>
 pkts bytes target     prot opt <span class="token keyword">in</span>     out     <span class="token builtin class-name">source</span>               destination         

Chain POSTROUTING <span class="token punctuation">(</span>policy ACCEPT <span class="token number">0</span> packets, <span class="token number">0</span> bytes<span class="token punctuation">)</span>
 pkts bytes target     prot opt <span class="token keyword">in</span>     out     <span class="token builtin class-name">source</span>               destination         
    <span class="token number">4</span>   <span class="token number">261</span> MASQUERADE  all  --  *      <span class="token operator">!</span>docker0  <span class="token number">172.17</span>.0.0/16        <span class="token number">0.0</span>.0.0/0           
    <span class="token number">0</span>     <span class="token number">0</span> MASQUERADE  tcp  --  *      *       <span class="token number">172.17</span>.0.3           <span class="token number">172.17</span>.0.3           tcp dpt:80

Chain OUTPUT <span class="token punctuation">(</span>policy ACCEPT <span class="token number">0</span> packets, <span class="token number">0</span> bytes<span class="token punctuation">)</span>
 pkts bytes target     prot opt <span class="token keyword">in</span>     out     <span class="token builtin class-name">source</span>               destination         
    <span class="token number">2</span>   <span class="token number">120</span> DOCKER     all  --  *      *       <span class="token number">0.0</span>.0.0/0           <span class="token operator">!</span><span class="token number">127.0</span>.0.0/8          ADDRTYPE match dst-type LOCAL

Chain DOCKER <span class="token punctuation">(</span><span class="token number">2</span> references<span class="token punctuation">)</span>
 pkts bytes target     prot opt <span class="token keyword">in</span>     out     <span class="token builtin class-name">source</span>               destination         
    <span class="token number">1</span>    <span class="token number">60</span> RETURN     all  --  docker0 *       <span class="token number">0.0</span>.0.0/0            <span class="token number">0.0</span>.0.0/0           
    <span class="token number">1</span>    <span class="token number">60</span> DNAT       tcp  --  <span class="token operator">!</span>docker0 *       <span class="token number">0.0</span>.0.0/0            <span class="token number">192.168</span>.203.138      tcp dpt:49153 to:172.17.0.3:80
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>  将容器端口映射到指定IP的随机端口</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token punctuation">[</span>root@localhost ~<span class="token punctuation">]</span><span class="token comment"># docker run -dit --name web1 -p 192.168.203.138::80 httpd</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p>  在另一个终端上查看端口映射情况</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token punctuation">[</span>root@localhost ~<span class="token punctuation">]</span><span class="token comment"># docker port web1</span>
<span class="token number">80</span>/tcp -<span class="token operator">&gt;</span> <span class="token number">192.168</span>.203.138:49153
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>

<h3 id="自定义docker0桥的网络属性信息"><a href="#自定义docker0桥的网络属性信息" class="headerlink" title="自定义docker0桥的网络属性信息"></a>自定义<code>docker0</code>桥的网络属性信息</h3><p>  自定义<code>docker0</code>桥的网络属性信息需要修改<code>/etc/docker/daemon.json</code>配置文件</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token punctuation">[</span>root@localhost ~<span class="token punctuation">]</span><span class="token comment"># cd /etc/docker/</span>
<span class="token punctuation">[</span>root@localhost docker<span class="token punctuation">]</span><span class="token comment"># vim daemon.json </span>
<span class="token punctuation">[</span>root@localhost docker<span class="token punctuation">]</span><span class="token comment"># systemctl daemon-reload</span>
<span class="token punctuation">[</span>root@localhost docker<span class="token punctuation">]</span><span class="token comment"># systemctl restart docker</span>

<span class="token punctuation">{</span>
    <span class="token string">"registry-mirrors"</span><span class="token builtin class-name">:</span> <span class="token punctuation">[</span><span class="token string">"https://4hygggbu.mirror.aliyuncs.com/"</span><span class="token punctuation">]</span>,
    <span class="token string">"bip"</span><span class="token builtin class-name">:</span> <span class="token string">"192.168.1.5/24"</span>
<span class="token punctuation">}</span>
EOF
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token punctuation">[</span>root@localhost ~<span class="token punctuation">]</span><span class="token comment"># vim /lib/systemd/system/docker.service </span>
<span class="token assign-left variable">ExecStart</span><span class="token operator">=</span>/usr/bin/dockerd <span class="token parameter variable">-H</span> fd:// <span class="token parameter variable">--containerd</span><span class="token operator">=</span>/run/containerd/containerd.sock <span class="token parameter variable">-H</span> tcp://0.0.0.0:2375  <span class="token parameter variable">-H</span> unix:///var/run/docker.sock

<span class="token punctuation">[</span>root@localhost ~<span class="token punctuation">]</span><span class="token comment"># systemctl daemon-reload</span>

<span class="token punctuation">[</span>root@localhost ~<span class="token punctuation">]</span><span class="token comment"># systemctl restart docker</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>  在客户端上向<code>dockerd</code>直接传递<code>“-H|–host”</code>选项指定要控制哪台主机上的docker容器</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token punctuation">[</span>root@localhost ~<span class="token punctuation">]</span><span class="token comment"># docker -H 192.168.203.138:2375 ps</span>
CONTAINER ID   IMAGE     COMMAND              CREATED             STATUS          PORTS                           NAMES
e97bc1774e40   httpd     <span class="token string">"httpd-foreground"</span>   <span class="token number">30</span> minutes ago      Up <span class="token number">11</span> seconds   <span class="token number">192.168</span>.203.138:49153-<span class="token operator">&gt;</span><span class="token number">80</span>/tcp   web1
af5ba32f990e   busybox   <span class="token string">"sh"</span>                 About an hour ago   Up <span class="token number">14</span> seconds                                   b3
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>
<p>  创建新网络</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token punctuation">[</span>root@localhost ~<span class="token punctuation">]</span><span class="token comment"># docker network create ljl -d bridge </span>
883eda50812bb214c04986ca110dbbcb7600eba8b033f2084cd4d750b0436e12

<span class="token punctuation">[</span>root@localhost ~<span class="token punctuation">]</span><span class="token comment"># docker network ls</span>
NETWORK ID     NAME      DRIVER    SCOPE
0c5f4f114c27   bridge    bridge    <span class="token builtin class-name">local</span>
8c2d14f1fb82   <span class="token function">host</span>      <span class="token function">host</span>      <span class="token builtin class-name">local</span>
883eda50812b   ljl       bridge    <span class="token builtin class-name">local</span>
85ed12d38815   none      null      <span class="token builtin class-name">local</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>  创建一个额外的自定义桥，区别于<code>docker0</code></p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token punctuation">[</span>root@localhost ~<span class="token punctuation">]</span><span class="token comment"># docker network create -d bridge --subnet "192.168.2.0/24" --gateway "192.168.2.1" br0</span>
af9ba80deb619de3167939ec5b6d6136a45dce90907695a5bc5ed4608d188b99

<span class="token punctuation">[</span>root@localhost ~<span class="token punctuation">]</span><span class="token comment"># docker network ls</span>
NETWORK ID     NAME      DRIVER    SCOPE
af9ba80deb61   br0       bridge    <span class="token builtin class-name">local</span>
0c5f4f114c27   bridge    bridge    <span class="token builtin class-name">local</span>
8c2d14f1fb82   <span class="token function">host</span>      <span class="token function">host</span>      <span class="token builtin class-name">local</span>
883eda50812b   ljl       bridge    <span class="token builtin class-name">local</span>
85ed12d38815   none      null      <span class="token builtin class-name">local</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>  使用新创建的自定义桥来创建容器：</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token punctuation">[</span>root@localhost ~<span class="token punctuation">]</span><span class="token comment"># docker run -it --name b1 --network br0 busybox</span>
/ <span class="token comment"># ifconfig </span>
eth0      Link encap:Ethernet  HWaddr 02:42:C0:A8:02:02  
          inet addr:192.168.2.2  Bcast:192.168.2.255  Mask:255.255.255.0
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:11 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0 
          RX bytes:962 <span class="token punctuation">(</span><span class="token number">962.0</span> B<span class="token punctuation">)</span>  TX bytes:0 <span class="token punctuation">(</span><span class="token number">0.0</span> B<span class="token punctuation">)</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>  再创建一个容器，使用默认的bridge桥：</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token punctuation">[</span>root@localhost ~<span class="token punctuation">]</span><span class="token comment"># docker run --name b2 -it busybox</span>
/ <span class="token comment"># ls</span>
bin   dev   etc   home  proc  root  sys   tmp   usr   var
/ <span class="token comment"># ifconfig </span>
eth0      Link encap:Ethernet  HWaddr 02:42:C0:A8:01:03  
          inet addr:192.168.1.3  Bcast:192.168.1.255  Mask:255.255.255.0
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:6 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0 
          RX bytes:516 <span class="token punctuation">(</span><span class="token number">516.0</span> B<span class="token punctuation">)</span>  TX bytes:0 <span class="token punctuation">(</span><span class="token number">0.0</span> B<span class="token punctuation">)</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<link rel="stylesheet" href="/css/spoiler.css" type="text/css"><script src="/js/spoiler.js" type="text/javascript" async></script>
    </div>

    
    
    

    <footer class="post-footer">
<div style="padding-top: 26px;">
    

    <div class="endlan">
        <i></i>
        <p>本文结束--- <img src="https://static.xiaosige.com/img/logo.png" style="display:inline-block;margin-bottom:-7px;height: 25px;"> ---感谢您的阅读</p>
    </div>


    <p id="hitokoto" style="text-align:center;margin-top: 30px;font-family: 'Palatino Linotype', 'Book Antiqua', Palatino, STKaiti, KaiTi, SimKai, DFKai-SB, 'Lato', 'PingFang SC', 'Microsoft YaHei', sans-serif;font-weight: bold;color: #999;">
     正在加载一言...
    </p>
    <div style="margin-top: 30px;">
      <img id="wechat_subscriber_qcode" src="https://static.xiaosige.com/img/reward-container-back.png" alt="leeze wechat" style="max-width: 100%;">
    </div>
    

    
</div>


          <div class="reward-container">
  <div>请我一杯咖啡吧！</div>
  <button>
    打赏
  </button>
  <div class="post-reward">
      <div>
        <img src="https://static.xiaosige.com/img/wechatpay.png" alt="leeze 微信支付">
        <span>微信支付</span>
      </div>
      <div>
        <img src="https://static.xiaosige.com/img/alipay.png" alt="leeze 支付宝">
        <span>支付宝</span>
      </div>

  </div>
</div>

          

<div class="post-copyright">
<ul>
  <li class="post-copyright-author">
      <strong>原文作者： </strong>leeze
  </li>
  <li class="post-copyright-link">
      <strong>本文链接：</strong>
      <a href="https://www.xiaosige.com/post/2f93af4e.html" title="Docker容器网络和Docker容器网络配置">https://www.xiaosige.com/post/2f93af4e.html</a>
  </li>
  <li class="post-copyright-license">
      <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/zh-CN" rel="noopener" target="_blank"><i class="fab fa-fw fa-creative-commons"></i>BY-NC-SA</a> 许可协议。转载请注明出处！
  </li>
</ul>
</div>

          <div class="post-tags">
              <a href="/tags/Docker/" rel="tag"><i class="fa fa-tag"></i> Docker</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/post/496907aa.html" rel="prev" title="Docker】之 Docker Compose v2 安装">
                  <i class="fa fa-angle-left"></i> Docker】之 Docker Compose v2 安装
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/post/7f65a2db.html" rel="next" title="Docker + Jenkins + gogs 自动化部署">
                  Docker + Jenkins + gogs 自动化部署 <i class="fa fa-angle-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






    <div class="comments" id="SOHUCS" sid="a6e572cd201d99ee76168d3e2dc50e9d"></div>
</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">

  <div class="copyright">
    &copy; 
    <span itemprop="copyrightYear">2025</span>
    <span class="with-love">
      <i class="fa fa-heart"></i>
    </span>
    <span class="author" itemprop="copyrightHolder">Xiaosige.com 版权所有</span>
  </div>
<div class="wordcount">
  <span class="post-meta-item">
    <span class="post-meta-item-icon">
      <i class="fa fa-chart-line"></i>
    </span>
    <span title="站点总字数">435k</span>
  </span>
  <span class="post-meta-item">
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
    <span title="站点阅读时长">6:35</span>
  </span>
</div>
<div class="busuanzi-count">
    <span class="post-meta-item" id="busuanzi_container_site_uv">
      <span class="post-meta-item-icon">
        <i class="fa fa-user"></i>
      </span>
      <span class="site-uv" title="总访客量">
        <span id="busuanzi_value_site_uv"></span>
      </span>
    </span>
    <span class="post-meta-item" id="busuanzi_container_site_pv">
      <span class="post-meta-item-icon">
        <i class="fa fa-eye"></i>
      </span>
      <span class="site-pv" title="总访问量">
        <span id="busuanzi_value_site_pv"></span>
      </span>
    </span>
</div>



<div calss="ypy" style="text-align:center;display:none;">
    本网站由
    <a target="_blank" rel="nofollow noopener" href="https://www.upyun.com/?utm_source=lianmeng&utm_medium=referral" style="border-bottom:none;">
        <img src="https://static.xiaosige.com/img/ypy_logo.png" style="display:inline-block;margin-bottom:-7px;height: 25px;-webkit-filter: brightness(.8);filter: brightness(.8);">
    </a>
    提供CDN加速/云存储服务
</div>


  <div class="beian">
          <img src="https://static.xiaosige.com/img/gongan.png" style="display: inline-block;vertical-align: text-bottom;padding-right: 6px;"><a href="http://www.beian.gov.cn/portal/registerSystemInfo?recordcode=11011502004362" rel="noopener" target="_blank">京公网安备 11011502004362 </a>
    <span></span><a href="http://beian.miit.gov.cn/" rel="noopener" target="_blank">京ICP备2020038036号-1 </a>
    <span></span>
    本网站由
    <a target="_blank" rel="nofollow noopener" href="https://www.upyun.com/?utm_source=lianmeng&utm_medium=referral" style="border-bottom:none;">
        <img src="https://static.xiaosige.com/img/ypy_logo.png" style="display:inline-block;margin-bottom:-7px;height: 25px;-webkit-filter: brightness(.8);filter: brightness(.8);">
    </a>
    提供CDN加速/云存储服务
  </div>


<link href="https://cdn.jsdelivr.net/npm/aplayer@1.10.1/dist/APlayer.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/aplayer@1.10.1/dist/APlayer.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/meting@2.0.1/dist/Meting.min.js"></script>
<meting-js server="netease" type="playlist" id="2228518256" fixed="true" autoplay="false" order="random" lrc-type=1  theme="#eb7aab"></meting-js>


<div class="bg-box" id="bg-box1"></div>
<div class="bg-box" id="bg-box2"></div>
<style>
.bg-box {
 background-repeat:no-repeat;
 background-attachment:fixed;
 background-position:50% 50%;
 background-size:cover;
 position:fixed;
 left:0;
 right:0;
 top:0;
 bottom:0
}
#bg-box1 {
 z-index:-998
}
#bg-box2 {
 z-index:-999
}
</style>




    </div>
  </footer>

  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>
  <div class="sidebar-dimmer"></div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>
<script class="next-config" data-name="changyan" type="application/json">{"enable":true,"appid":"cyvSPOTJq","appkey":"4436699688bbb9caa6e8826551a7c0f7"}</script>
<script src="/js/third-party/comments/changyan.js" defer></script>
<!-- 提示信息 -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/jquery-toast-plugin@1.3.2/dist/jquery.toast.min.css"/>
<script src="https://cdn.jsdelivr.net/npm/jquery-toast-plugin@1.3.2/dist/jquery.toast.min.js"></script>
<!-- 樱花特效(https://cdn.jsdelivr.net/gh/yremp/yremp-js@1.5/sakura.js) -->
<!-- 下雪(圣诞) -->

<!-- 天气 -->

<!-- 文字闪烁（变色） -->
<script>
function magicColor(mode,t){
  t=t||10;
  let elem=document.getElementsByClassName("magic-color");
  if(!elem){
      setTimeout(function(){
          magicColor(mode,t-1);
      },400);
      return;
  }
  if(window.mcHandler==undefined){
      window.mcHandler={elements:[]};
      window.mcHandler.colorIndex=0;
      window.mcHandler.run=function(mode){
          let color=mode=="random"?("rgb("+Math.floor(Math.random()*256)+","+Math.floor(Math.random()*256)+","+Math.floor(Math.random()*256)+",1)"):["#CC0000","#9999CC","#CC3366","#669999","#FFCC00","#00CCCC","#CC00CC"][(window.mcHandler.colorIndex++)%7];
          for(var i=0,L=window.mcHandler.elements.length;i<L;i++)window.mcHandler.elements[i].style.color=color;
      }
  }
  window.mcHandler.elements=elem;
  if(window.mcHandler.timer==undefined){
      window.mcHandler.timer=setInterval(()=>{window.mcHandler.run(mode)},500);
  }
}
magicColor("random");//random为随机颜色，否则为固定颜色随机；上方“闪烁（变色）”字样为固定颜色随机
</script>


<!-- 一言API -->
<!-- 现代写法，推荐 -->
<!-- 兼容低版本浏览器 (包括 IE)，可移除 -->
<script src="https://cdn.jsdelivr.net/npm/bluebird@3.7.2/js/browser/bluebird.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/fetch@1.1.0/lib/fetch.min.js"></script>
<!--End-->
<script>
fetch('https://v1.hitokoto.cn')
  .then(function (res){
    return res.json();
  })
  .then(function (data) {
    var hitokoto = document.getElementById('hitokoto');
    if(hitokoto){
      hitokoto.innerHTML = "<i class='fa fa-volume-up magic-color' style='margin-right:6px;'></i>" + data.hitokoto + '——【' + data.from + '】';
    }
  })
  .catch(function (err) {
    console.error(err);
  })
</script>


<!-- 代码块自动隐藏 -->
<script>
$(function(){
    const CODE_MAX_HEIGHT = 200;
    const containers = [];

    // 展开
    $('body').on('click', '.js_unfold_code_btn', function () {
        $(this).closest('.js_highlight_container').addClass('on');
    });
    // 收起
    $('body').on('click', '.js_retract_code_btn', function () {
        const $container = $(this).closest('.js_highlight_container').removeClass('on');
        const winTop = $(window).scrollTop();
        const offsetTop = $container.offset().top;
        $(this).css('top', 0);
        if (winTop > offsetTop) {
            // 设置滚动条位置
            $('body, html').animate({
                scrollTop: $container.offset().top - CODE_MAX_HEIGHT
            }, 600);
        }
    });
    // 滚动事件，触发动画效果
    $(window).on('scroll', function () {
        const scrollTop = $(window).scrollTop();
        const temp = [];
        for (let i = 0; i < containers.length; i++) {
            const item = containers[i];
            const { $container, height, $hide, hasHorizontalScrollbar } = item;
            if ($container.closest('body').length === 0) {
                // 如果 $container 元素已经不在页面上, 则删除该元素
                // 防止pjax页面跳转之后，元素未删除
                continue;
            }
            temp.push(item);
            if (!$container.hasClass('on')) {
                continue;
            }
            const offsetTop = $container.offset().top;
            const hideBtnHeight = $hide.outerHeight();
            // 减去按钮高度，减去底部滚动条高度
            const maxTop = parseInt(height - (hasHorizontalScrollbar ? 17 : 0) - hideBtnHeight);
            let top = parseInt(
                Math.min(
                    Math.max(scrollTop - offsetTop, 0), // 如果小于 0 ，则取 0
                    maxTop,// 如果大于 height ，则取 height
                )
            );
            // 根据 sin 曲线设置"收起阅读"位置
            const halfHeight = parseInt($(window).height() / 2 * Math.sin((top / maxTop) * 90 * (2 * Math.PI/360)));
            $hide.css('top', Math.min(top + halfHeight, maxTop));
        }
        //containers = temp;
    });

    // 添加隐藏容器
    const addCodeWrap = ($node) => {
        const $container = $node.wrap('<div class="js_highlight_container highlight-container"><div class="highlight-wrap"></div></div>').closest('.js_highlight_container');

        // 底部 "阅读更多" 与 侧边栏 "收起阅读"
        const $btn = $(`
        <div class="highlight-footer">
          <a class="js_unfold_code_btn show-btn" href="javascript:;">
              <span class="btn-inner">
                阅读更多<i class="fa fa-angle-right fa-lg" aria-hidden="true"></i>
              </span>
              <div class="btnbg-x"></div>
          </a>
        </div>
        <a class="js_retract_code_btn hide-btn" href="javascript:;"><i class="fa fa-angle-up fa-lg" aria-hidden="true"></i>收起阅读</a>
      `);

        $container.append($btn);
        return $container;
    };

    $('.highlight').each(function () {
        // 防止重复渲染
        if (this.__render__ === true) {
            return true;
        }
        this.__render__ = true;
        const $this = $(this);
        const height = $(this).outerHeight();
        if (height > CODE_MAX_HEIGHT) {
            // 添加展开&收起容器
            const $container = addCodeWrap($this, height);
            containers.push({
                $container,
                height,
                $hide: $container.find('.js_retract_code_btn'),
                hasHorizontalScrollbar: this.scrollWidth > this.offsetWidth,
            });
        }
    });

    $('.line-numbers').each(function () {
        // 防止重复渲染
        if (this.__render__ === true) {
            return true;
        }
        this.__render__ = true;
        const $this = $(this);
        const height = $(this).outerHeight();
        if (height > CODE_MAX_HEIGHT) {
            // 添加展开&收起容器
            const $container = addCodeWrap($this, height);
            containers.push({
                $container,
                height,
                $hide: $container.find('.js_retract_code_btn'),
                hasHorizontalScrollbar: this.scrollWidth > this.offsetWidth,
            });
        }
    });

    $('.table-container').each(function () {
        // 防止重复渲染
        if (this.__render__ === true) {
            return true;
        }
        this.__render__ = true;
        const $this = $(this);
        const height = $(this).outerHeight();
        if (height > CODE_MAX_HEIGHT) {
            // 添加展开&收起容器
            const $container = addCodeWrap($this, height);
            containers.push({
                $container,
                height,
                $hide: $container.find('.js_retract_code_btn'),
                hasHorizontalScrollbar: this.scrollWidth > this.offsetWidth,
            });
        }
    });

});
</script>


<script  type="text/javascript">

layui.use(['jquery', 'layer'], function(){

  var $ = layui.$,layer = layui.layer;

  <!-- wobble窗口摆动特效 -->
  


     var wobbleWindow = function(object, params) {
          var canvas,
              ctx;
          var mousePos = {
              x: 0,
              y: 0
          };
          var isResizing = false;
          var delayId = 0;
          var canvasContent = {};
          var points = {};

          var settings = {};
          settings.name = 'wobblew'; //name
          settings.position = 'relative'; //relative or absolute
          settings.depth = -1; //depth for zIndex
          settings.overflowX = 'visible';
          settings.overflowY = 'visible';
          settings.offsetX = 0; //+ or - value the size of the div
          settings.offsetY = 0; //+ or - value the size of the div
          settings.moveTypeIn = 'move'; //method points follow the mouse
          settings.moveTypeOut = 'wobble'; //method points go back to init position
          settings.wobbleFactor = 0.95; //control the wobble effect
          settings.wobbleSpeed = 0.1; //control the wobble effect
          settings.moveSpeed = 6; //control the move speed
          settings.lineWidth = 1; //lineWidth

          settings.transplantLineColor = false; //true Use Object border-color
          settings.lineColor = ''; //no value = no line. Use hex/rgba values
          settings.transplantBodyColor = true; //true Use Object background Color
          settings.bodyColor = ''; //no value = no body color. Use hex/rgba values
          settings.radius = 50; //
          settings.pointCountX = 7; //quantity of points horizontal. must be an odd int
          settings.pointCountY = 5; //quantity of points vertical. must be an odd int
          settings.movementLeft = true; //enable/disable movement directions
          settings.movementRight = true; //enable/disable movement directions
          settings.movementTop = true; //enable/disable movement directions
          settings.movementBottom = true; //enable/disable movement directions
          settings.autoResize = true; //if true size will be automatically adjusted
          settings.debug = false; //enable/disable debug mode

          // ---
          if (params !== undefined) {
              for (var prop in params) {
                  if (params.hasOwnProperty(prop) && settings.hasOwnProperty(prop)) {
                      settings[prop] = params[prop];
                  }
              }
          }

          // ---
          if (!object) {
              throw Error('\n' + 'No div element found');
          }
          if ((settings.pointCountX % 2) === 0) {
              throw Error('\n' + 'Param pointCountX must be an odd integer');
          }
          if ((settings.pointCountY % 2) === 0) {
              throw Error('\n' + 'Param pointCountY must be an odd integer');
          }

          // ---
          HTMLElement.prototype.__defineGetter__("currentStyle", function() {
              return this.ownerDocument.defaultView.getComputedStyle(this, null);
          });
          // ---
          function init() {
              canvas = document.createElement('canvas');
              canvas.id = settings.name;
              canvas.style.position = 'absolute';
              canvas.style.zIndex = settings.depth.toString();
              canvas.addEventListener('mousemove', mouseMoveHandler);
              canvas.addEventListener('mouseleave', mouseLeaveHandler);
              ctx = canvas.getContext('2d');

              // element.insertBefore(canvas, element.firstChild);
              object.appendChild(canvas);
              object.style.position = settings.position;
              object.style.zIndex = (settings.depth + 1).toString();
              if (settings.overflowX.length > 0) {
                  object.parentElement.style.overflowX = settings.overflowX;
              };
              if (settings.overflowY.length > 0) {
                  object.parentElement.style.overflowY = settings.overflowY;
              };
              if (settings.transplantBodyColor) {
                  if (object.currentStyle.backgroundColor.length > 0) {
                      settings.bodyColor = object.currentStyle.backgroundColor;
                  }
              };
              if (settings.transplantLineColor) {
                  if (object.currentStyle.borderColor.length > 0) {
                      settings.lineColor = object.currentStyle.borderColor;
                  }
              };
              canvasContent.elementWidth = object.offsetWidth;
              canvasContent.elementHeight = object.offsetHeight;
              // ---
              resizeCanvas();
              addWindow();
              animloop();
              // -----------
              if (settings.transplantBodyColor) {
                  if (object.currentStyle.backgroundColor.length > 0) {
                      if (object.className.length > 0) {
                          object.className += ' wobbleTransparentBK';
                      } else {
                          object.className = ' wobbleTransparentBK';
                      };
                  }
              };
              if (settings.transplantLineColor) {
                  if (object.currentStyle.borderColor.length > 0) {
                      if (object.className.length > 0) {
                          object.className += ' wobbleTransparentLine';
                      } else {
                          object.className = ' wobbleTransparentLine';
                      };
                  }
              };
          };

          // ---
          function resizeCanvas() {
              canvasContent.width = canvasContent.elementWidth + settings.offsetX * 2;
              canvasContent.height = canvasContent.elementHeight + settings.offsetY * 2;

              if (settings.radius > 0) { //round,  ceil
                  settings.pointCountX = Math.round(canvasContent.width / settings.radius);
                  settings.pointCountY = Math.round(canvasContent.height / settings.radius);
              };
              if (settings.pointCountX % 2 == 0) {
                  settings.pointCountX = settings.pointCountX + 1;
              };
              if (settings.pointCountY % 2 == 0) {
                  settings.pointCountY = settings.pointCountY + 1;
              };

              points.spaceX = Math.min(canvasContent.elementWidth, canvasContent.width / (settings.pointCountX - 1));
              points.spaceY = Math.min(canvasContent.elementHeight, canvasContent.height / (settings.pointCountY + 1));
              points.radius = Math.ceil(Math.max(points.spaceX, points.spaceY));

              ///--------------new1------------------
              canvasContent.left = 0;
              canvasContent.top = 0;
              settings.canvasWidth = canvasContent.elementWidth;
              if (settings.movementLeft) {
                  canvas.style.left = -points.radius + 'px';
                  settings.canvasWidth += points.radius;
                  canvasContent.left = points.radius - settings.offsetX;
              } else {
                  canvas.style.left = -settings.offsetX + 'px';
              };
              if (settings.movementRight)
                  settings.canvasWidth += points.radius;

              settings.canvasHeight = canvasContent.elementHeight;
              if (settings.movementTop) {
                  canvas.style.top = -points.radius + 'px';
                  settings.canvasHeight += points.radius;
                  canvasContent.top = points.radius - settings.offsetY;
              } else {
                  canvas.style.top = -settings.offsetY + 'px';
              };
              if (settings.movementBottom)
                  settings.canvasHeight += points.radius;

              canvas.width = settings.canvasWidth;
              canvas.height = settings.canvasHeight;
          };

          // ---
          function addWindow() {
              points.pointHolder = [];
              // ---
              var point;
              var flag;
              var i,
                  l;
              // ---
              //top
              flag = true;
              for (i = 0, l = settings.pointCountX; i < l; i++) {
                  if (settings.movementTop) {
                      if (flag) {
                          point = addPoint(canvasContent.left + i * points.spaceX, canvasContent.top, 0, 0, 0, true, points.spaceX, 'P', settings.debug);
                          flag = false;
                      } else {
                          point = addPoint(canvasContent.left + i * points.spaceX, canvasContent.top, 0, 0, 0, true, points.spaceX, 'C', settings.debug);
                          flag = true;
                      }
                      if (i === 0 || i === l - 1) {
                          point.color = '#00FF00';
                          point.movement = false;
                      }
                      points.pointHolder.push(point);
                  } else {
                      if (i === 0 || i === l - 1) {
                          point = addPoint(canvasContent.left + i * points.spaceX, canvasContent.top, 0, 0, 0, false, 0, 'P', settings.debug);
                      }
                      points.pointHolder.push(point);
                  }
              }

              // ---
              //right
              flag = false;
              for (i = 1, l = settings.pointCountY + 1; i < l; i++) {
                  if (settings.movementRight) {
                      if (flag) {
                          point = addPoint(canvasContent.left + canvasContent.width, canvasContent.top + i * points.spaceY, 0, 0, 0, true, points.spaceY, 'P', settings.debug);
                          flag = false;
                      } else {
                          point = addPoint(canvasContent.left + canvasContent.width, canvasContent.top + i * points.spaceY, 0, 0, 0, true, points.spaceY, 'C', settings.debug);
                          flag = true;
                      }
                      points.pointHolder.push(point);
                  } else {
                      if (i === 1) {
                          point = addPoint(canvasContent.left + canvasContent.width, canvasContent.top + (i - 1) * points.spaceY, 0, 0, 0, false, 0, 'P', settings.debug);
                      } else if (i === settings.pointCountY) {
                          point = addPoint(canvasContent.left + canvasContent.width, canvasContent.top + (i + 1) * points.spaceY, 0, 0, 0, false, 0, 'P', settings.debug);
                      }
                      points.pointHolder.push(point);
                  }
              }

              // ---
              //bottom
              flag = true;
              for (i = settings.pointCountX - 1, l = -1; i > l; i--) {
                  if (settings.movementBottom) {
                      if (flag) {
                          point = addPoint(canvasContent.left + i * points.spaceX, canvasContent.top + canvasContent.height, 0, 0, 0, true, points.spaceX, 'P', settings.debug);
                          flag = false;
                      } else {
                          point = addPoint(canvasContent.left + i * points.spaceX, canvasContent.top + canvasContent.height, 0, 0, 0, true, points.spaceX, 'C', settings.debug);
                          flag = true;
                      }
                      if (i === 0 || i === settings.pointCountX - 1) {
                          point.color = '#00FF00';
                          point.movement = false;
                      }
                      points.pointHolder.push(point);
                  } else {
                      if (i === 0 || i === settings.pointCountX - 1) {
                          point = addPoint(canvasContent.left + i * points.spaceX, canvasContent.top + canvasContent.height, 0, 0, 0, false, 0, 'P', settings.debug);
                      }
                      points.pointHolder.push(point);
                  }
              }

              // ---
              //left
              flag = false;
              for (i = settings.pointCountY, l = -1; i > l; i--) {
                  if (settings.movementLeft) {
                      if (flag) {
                          point = addPoint(canvasContent.left, canvasContent.top + i * points.spaceY, 0, 0, 0, true, points.spaceY, 'P', settings.debug);
                          flag = false;
                      } else {
                          point = addPoint(canvasContent.left, canvasContent.top + i * points.spaceY, 0, 0, 0, true, points.spaceY, 'C', settings.debug);
                          flag = true;
                      }
                      points.pointHolder.push(point);
                  } else {
                      if (i === 0) {
                          point = addPoint(canvasContent.left, canvasContent.top + i * points.spaceY, 0, 0, 0, false, 0, 'P', settings.debug);
                      } else if (i === settings.pointCountY) {
                          point = addPoint(canvasContent.left, canvasContent.top + (i + 1) * points.spaceY, 0, 0, 0, false, 0, 'P', settings.debug);
                      }
                      points.pointHolder.push(point);
                  }
              }
          }

          // ---
          function addPoint(x, y, xp, yp, distance, movement, radius, type, visible) {
              var point = {};
              point.x = x;
              point.y = y;
              point.xp = x;
              point.yp = y;
              point.sx = 0;
              point.sy = 0;
              point.distance = distance;
              point.movement = movement;
              point.radius = radius;
              point.type = type;
              point.visible = visible;
              return point;
          };

          // ---
          window.requestAnimFrame = (function() {
              return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || function(callback) {
                  window.setTimeout(callback, 1000 / 60);
              };
          })();

          function animloop() {
              requestAnimFrame(animloop);
              render();
              if (settings.autoResize) {
                  resize();
              }
          };

          // ---
          function render() {
              ctx.clearRect(0, 0, settings.canvasWidth, settings.canvasHeight);

              // ---
              var windowPoints = points.pointHolder;
              var i,
                  l;

              // ---
              ctx.beginPath();
              ctx.moveTo(windowPoints[0].x, windowPoints[0].y);
              for (i = 1, l = windowPoints.length; i < l; i += 2) {
                  var point = windowPoints[i];

                  // ---
                  var dx = mousePos.x - point.xp;
                  var dy = mousePos.y - point.yp;
                  point.distance = Math.sqrt(dx * dx + dy * dy);
                  if (point.distance < point.radius) {
                      if (settings.moveTypeIn === 'wobble') {
                          point.sx = point.sx * settings.wobbleFactor + (mousePos.x - point.x) * settings.wobbleSpeed;
                          point.sy = point.sy * settings.wobbleFactor + (mousePos.y - point.y) * settings.wobbleSpeed;
                          point.x = point.x + point.sx;
                          point.y = point.y + point.sy;
                      } else if (settings.moveTypeIn === 'move') {
                          point.x -= (point.x - mousePos.x) / settings.moveSpeed;
                          point.y -= (point.y - mousePos.y) / settings.moveSpeed;
                      }
                  } else {
                      if (settings.moveTypeOut === 'wobble') {
                          point.sx = point.sx * settings.wobbleFactor + (point.xp - point.x) * settings.wobbleSpeed;
                          point.sy = point.sy * settings.wobbleFactor + (point.yp - point.y) * settings.wobbleSpeed;
                          point.x = point.x + point.sx;
                          point.y = point.y + point.sy;
                      } else if (settings.moveTypeOut === 'move') {
                          point.x -= (point.x - point.xp) / settings.moveSpeed;
                          point.y -= (point.y - point.yp) / settings.moveSpeed;
                      }
                  }

                  // ---
                  var pointBefor = windowPoints[i - 1];
                  var pointAfter = windowPoints[i + 1];
                  if (i > 2 && i < windowPoints.length - 2) {
                      if (pointBefor.movement) {
                          pointBefor.x = (windowPoints[i - 2].x + point.x) / 2;
                          pointBefor.y = (windowPoints[i - 2].y + point.y) / 2;
                      }
                      if (pointAfter.movement) {
                          pointAfter.x = (windowPoints[i + 2].x + point.x) / 2;
                          pointAfter.y = (windowPoints[i + 2].y + point.y) / 2;
                      }
                  }
                  ctx.quadraticCurveTo(point.x, point.y, pointAfter.x, pointAfter.y);
              }

              // ---
              if (settings.lineColor.length > 0) {
                  ctx.lineWidth = settings.lineWidth;
                  ctx.strokeStyle = settings.lineColor;
                  ctx.stroke();
              }
              if (settings.bodyColor.length > 0) {
                  ctx.fillStyle = settings.bodyColor;
                  ctx.fill();
              }
              // ctx.globalCompositeOperation = 'source-out';
              // ctx.fillStyle = "rgba(0, 0, 0, 1)";
              // ctx.fill();

              // ---
              if (settings.debug) {
                  for (i = 0, l = windowPoints.length; i < l; i++) {
                      var point = windowPoints[i];
                      if (point.visible) {
                          if (point.type === 'P') {
                              drawCircle(point.x, point.y, 3, '#FF0000');
                          } else {
                              drawCircle(point.x, point.y, 6, '#FF00FF');
                          }
                          if (point.color) {
                              drawCircle(point.x, point.y, 12, point.color);
                          }
                      }
                  }
                  ctx.strokeStyle = '#000000';
                  ctx.strokeRect(0, 0, settings.canvasWidth, settings.canvasHeight);
              }
          };

          // ---
          function delayFlag() {
              resizeCanvas();
              addWindow();
              isResizing = false;
          };

          function resize() {
              if (!isResizing) {
                  if (canvasContent.elementWidth !== object.offsetWidth || canvasContent.elementHeight !== object.offsetHeight) {
                      // -----------
                      isResizing = true;
                      canvasContent.elementWidth = object.offsetWidth;
                      canvasContent.elementHeight = object.offsetHeight;
                      // 防止闪白
                      delayId = window.setTimeout(delayFlag, 10);
                  }
              }
          };

          // ---
          function drawCircle(x, y, radius, color) {
              ctx.beginPath();
              ctx.arc(x, y, radius, 0, 2 * Math.PI);
              ctx.strokeStyle = color;
              ctx.stroke();
          };

          // ---
          function mouseMoveHandler(event) {
              mousePos = getMousePos(canvas, event);
          };

          function mouseLeaveHandler(event) {
              mousePos.x = -10000;
              mousePos.y = -10000;
          };

          // ---
          function getMousePos(canvas, event) {
              var rect = canvas.getBoundingClientRect();
              return {
                  x: event.clientX - rect.left,
                  y: event.clientY - rect.top
              };
          };

          // ---
          init();
      };


  var settings = {
        radius: 20,
        wobbleFactor: 0.98,
        wobbleSpeed: 0.05,
        moveSpeed: 3,
        lineWidth: 3,
        lineColor: '#000',
        bodyColor: '#EEE'

  };
/*
  var footers=document.querySelectorAll(".footer");
  wobbleWindow(footers[footers.length-1],{
                radius: 20,
                depth:-2,
                movementBottom: false,
                movementLeft: false,
                movementRight: false,
                debug: false
  });*/

  var postblocks=document.querySelectorAll(".main-inner .post-block ");
  [].forEach.call(postblocks, function(elm) {
      wobbleWindow(elm,settings);
  });

  

});

</script>


<!-- 页面背景图片动态加载 -->
<script>

     //获取指定长度的uuid
     function uuid(len, radix) {
        var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
        var uuid = [], i;
        radix = radix || chars.length;

        if (len) {
          // Compact form
          for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random()*radix];
        } else {
          // rfc4122, version 4 form
          var r;

          // rfc4122 requires these characters
          uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
          uuid[14] = '4';

          // Fill in random data.  At i==19 set the high bits of clock sequence as
          // per rfc4122, sec. 4.1.5
          for (i = 0; i < 36; i++) {
            if (!uuid[i]) {
              r = 0 | Math.random()*16;
              uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
            }
          }
        }

        return uuid.join('');
    }

    function animatechangbgimg(elm,opacityvalue,bgimgurl){
        $(elm).animate(
        　　{opacity:opacityvalue},
        　　"slow",
        　　null,
        　　function(){
               $(elm).css("background-image","url("+bgimgurl+")");
        　　}
        );
    }

    function checktime(time){
        var oldtime = localStorage.getItem("pjax-imgurl-leeze-lastvisitedtime");
        return Math.floor(((new Date).getTime()-oldtime)/1e3) >= time;
    }

    function changbgimgurl(){

          if(checktime(13)){//每次打开新页面，都会触发一个新的调度器，固加入lastvisitedtime校验，确保循环时间
                //var tc = "https://cdn.jsdelivr.net/gh/maplesugarr/blog-assets/imgs/body-bg/body-bg-" + Math.floor(23 * Math.random()) + ".jpg";
                //var bgimgurl = 'https://source.unsplash.com/collection/30327996/2000x1000';
                //var initbgurl = null,newbgurl = "https://cdn.jsdelivr.net/gh/leeze2012/blog-assets/img/body-bg-" + Math.floor(26 * Math.random()) + ".jpg";
                var initbgurl = null,newbgurl = "https://static.xiaosige.com/img/bg/body-bg-" + Math.floor(26 * Math.random()) + ".jpg";
                if(localStorage.hasOwnProperty('pjax-imgurl-leeze')){
                  initbgurl = localStorage.getItem("pjax-imgurl-leeze");
                }else{
                  initbgurl = newbgurl;
                }

                if($("#bg-box1").css('opacity')==="1"){
                      animatechangbgimg("#bg-box1",0,newbgurl);
                      animatechangbgimg("#bg-box2",1,initbgurl);
                }else{
                      animatechangbgimg("#bg-box1",1,initbgurl);
                      animatechangbgimg("#bg-box2",0,newbgurl);
                }

                localStorage.setItem("pjax-imgurl-leeze", newbgurl);
                localStorage.setItem("pjax-imgurl-leeze-lastvisitedtime",(new Date).getTime());
          }

    };

    setInterval(changbgimgurl,15000);

</script>

<!-- 标题文字闪烁效果 -->
<script>

document.getElementsByClassName('site-title')[0].setAttribute('data-splitting','chars');

Splitting();
gsap.set('.char', {
  '--hue': gsap.utils.distribute({
    base: 0,
    amount: 330,
  })
});
gsap.to('.char', {
  '--weight': 700,
  '--saturation': 80,
  ease: 'sine.inOut',
  duration: 0.5,
  stagger: {
    yoyo: true,
    repeat: -1,
    each: 0.15,
  }
}).time(2);
</script>


<script type="text/javascript">
    $(document).ready(function() {
        <!-- 站点作者头像 -->
        if($('.site-author:first').children().first().prop("tagName").toLowerCase() === "img"){
            <!-- 头像站点作者头像连接到关于我 -->
            $('.site-author-image').prop('outerHTML', "<a href='/about' title='关于我'>"+$('.site-author-image').prop("outerHTML")+"</a>");
            <!-- 站点作者头像动画阴影 -->
            $(".site-author-image").hover(function(){
                $(this).toggleClass('site-author-image-yy');
            },function(){
                $(this).toggleClass('site-author-image-yy');
            });
        }
        <!-- 五星好评 -->
        if($("#wpac-rating").length > 0){
            $("#wpac-rating").before("<div style='color: rgba(0, 0, 0, 0.75); font-size:13px; letter-spacing:3px'>(&gt; 看完记得五星好评哦亲 &lt;)</div>");
            $(".wp_rating").css("height","30px");
        }
        if($(".copyright").length > 0){
            <!-- footer追加邮箱 -->
            if($(".leezeEmail").length === 0){
                $(".copyright").append("<span class='leezeEmail post-meta-item'><i style='margin-right:6px;' class='fa fa-fw fa-envelope with-love'></i><a href='mailto:leeze0216@163.com' title='E-Mail → mailto:leeze0216@163.com' target='_blank'>leeze0216@163.com</a></span>");
            }
            <!-- 版权图标 -->
            $(".copyright span[class='with-love']").css("display","none");
        }
        <!-- footer的阅读次数位置调整 -->
        if($(".busuanzi-count").length > 0){
            $(".wordcount").append($(".busuanzi-count").html());
            $(".busuanzi-count").remove();
        }
        <!-- 标签页追加抖动样式 -->
        if($('.tag-cloud-tags a').length > 0){
            $('.tag-cloud-tags a').each(function(){
              $(this).addClass('shake shake-slow');
            });
        }
        <!-- 社交链接增加hover样式 -->
        if($('.links-of-author-item a').length > 0){
            $('.links-of-author-item a').each(function(index,element){
                if((index+1)%2 === 1){
                    $(this).addClass('hvr-bounce-to-right');
                }else{
                    $(this).addClass('hvr-bounce-to-left');
                }
                if($(this).children('i').length > 0){
                    $(this).children('i').addClass('faa-spin');
                }
            });
        }
        <!-- 主菜单hover样式 -->
        if($('.main-menu .menu-item a').length > 0){
            $('.main-menu .menu-item a').each(function(index,element){
                $(this).addClass('hvr-grow-shadow');
                if($(this).children('i').length > 0){
                    $(this).children('i').addClass('faa-wrench');
                }
            });
        }
        <!-- 移动端 隐藏音乐 -->
        if (/(iPhone|iPad|iPod|iOS|Android)/i.test(navigator.userAgent)) {
            $('meting-js').css('display','none');
        }

        <!-- 转载 -->
        if($('.zhuanzai').length > 0){
            $('.zhuanzai').each(function(index,element){
                $(this).hover(function(){
                    var tipmsg = this.getAttribute('href');
                    if( tipmsg === 'javascript:;'){
                        tipmsg = "抱歉，忘记转载地址了！";
                    }
                    layer.tips(tipmsg, $(this), {
                      tips: 3
                    });
                },function(){
                    layer.closeAll('tips');
                });
            });
        }

    });
</script>
<!-- 自定义 -->
<script src="/zone/js/leeze.js"></script>
<div class="moon-menu">
  <div class="moon-menu-items">
    
    <div id="moon-menu-item-back2bottom" class="moon-menu-item" onclick="back2bottom()">
      <i class='fa fa-chevron-down'></i>    </div>
    
    <div id="moon-menu-item-back2top" class="moon-menu-item" onclick="back2top()">
      <i class='fa fa-chevron-up'></i>    </div>
    
  </div>
  <div class="moon-menu-button">
    <svg class="moon-menu-bg">
      <circle class="moon-menu-cricle" cx="50%" cy="50%" r="44%"></circle>
      <circle class="moon-menu-border" cx="50%" cy="50%" r="48%"></circle>
    </svg>
    <div class="moon-menu-content">
      <div class="moon-menu-icon"><i class='fas fa-ellipsis-v'></i></div>
      <div class="moon-menu-text"></div>
    </div>
  </div>
</div><script src="/js/injector.js"></script><!-- hexo-inject:begin --><!-- hexo-inject:end -->
</body>
</html>
